2011-02-09 7 views
14

Me gustaría permitir que los usuarios de mi aplicación utilicen sus propias fuentes en la aplicación, copiándolas dentro del directorio de Documentos (a través de iTunes). Sin embargo, no puedo encontrar una forma de utilizar fuentes personalizadas de esta manera, ya que la forma correcta de hacerlo depende de usar la clave UIAppFonts en la aplicación Info.plist.iOS: Agregue fuente personalizada mediante programación durante el tiempo de ejecución

¿Hay alguna manera de anular esto durante el tiempo de ejecución?

Gracias.

Respuesta

1

Hay una clase creada por los chicos de Zynga que permite cargar cualquier fuente personalizada: FontLabel.

Debe llamar al [FontManager loadFont:] en el inicio de su aplicación (por ejemplo, en el delegado de su aplicación) para cada fuente que desee utilizar en su aplicación.

Por lo tanto, no es trivial iterar en la carpeta Documentos buscando archivos .ttf (la biblioteca solo funciona con la fuente ttf).

Un pequeño aviso: esta clase usa una subclase de UILabel.

+0

Gracias, esto parece bastante válida, pero me esperaba una mejor solución. Después de todo, estoy usando una UITextView para mostrar texto. – Vicarius

18

Sé que esta es una vieja pregunta, pero estaba tratando de hacer lo mismo hoy y encontré una forma de usar CoreText y CGFont.

En primer lugar, asegúrese de agregar el marco CoreText y

#import <CoreText/CoreText.h> 

Entonces esto debe hacerlo (en este ejemplo estoy usando una fuente previamente he descargado y guardado en un directorio de fuentes dentro del directorio de documentos):

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString * documentsDirectory = [paths objectAtIndex:0]; 
    NSString * fontPath = [documentsDirectory stringByAppendingPathComponent:@"Fonts/Chalkduster.ttf"]; 
    NSURL * url = [NSURL fileURLWithPath:fontPath]; 
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url); 
    CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider); 
    NSString * newFontName = (__bridge NSString *)CGFontCopyPostScriptName(newFont); 
    CGDataProviderRelease(fontDataProvider); 
    CFErrorRef error; 
    CTFontManagerRegisterGraphicsFont(newFont, &error); 
    CGFontRelease(newFont); 

    UIFont * finalFont = [UIFont fontWithName:newFontName size:20.0f]; 

Espero que ayude a cualquiera a tropezar con esta pregunta!

+0

Lo hice usar este método, gracias –

+0

Hola tengo una pregunta ... Actualmente, en tiempo de ejecución, estoy tomando la fuente del servicio web y que puedo instalarla y usarla, y ¿cómo? –

+0

Puede guardarlo en el directorio de Documentos de su aplicación y luego cargarlo usando el código anterior. – Pablo

6

prueba este

#import "MBProgressHUD.h" 
#import <CoreText/CoreText.h> 


- (void)viewDidLoad 
{ 
    NSURL *fileNameURL=[NSURL URLWithString:@"http://www.ge.tt/api/1/files/6d7jEnk/0/"]; 
    NSMutableURLRequest *filenameReq=[[NSMutableURLRequest alloc] initWithURL:fileNameURL]; 
    NSData *responseData=[NSURLConnection sendSynchronousRequest:filenameReq returningResponse:nil error:nil]; 

    NSDictionary* json = [NSJSONSerialization 
          JSONObjectWithData:responseData 
          options:kNilOptions 
          error:nil]; 


    NSString *fontFileName=[[[json valueForKey:@"filename"] componentsSeparatedByString:@"."] objectAtIndex:0]; 

    NSLog(@"file name is %@",fontFileName); 

    NSURL *url=[NSURL URLWithString:@"http://www.ge.tt/api/1/files/6d7jEnk/0/blob?download"]; 

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc] initWithURL:url]; 

    __block NSError *error; 
    __block NSURLResponse *response; 

    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES]; 
    [email protected]"Changing Font.."; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ 

     NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

     NSString *rootPath=[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents"]]; 
     NSString *filePath=[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.ttf",fontFileName]]; 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      [MBProgressHUD hideAllHUDsForView:self.view animated:YES]; 

      NSFileManager *fm=[NSFileManager defaultManager]; 

      if (![fm fileExistsAtPath:filePath]) { 
       [urlData writeToFile:filePath atomically:YES]; 
      } 

      NSString *rootPath=[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents"]]; 
      NSString *filePath=[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.ttf",fontFileName]]; 

      NSURL * fonturl = [NSURL fileURLWithPath:filePath]; 
      CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fonturl); 

      CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider); 
      NSString * newFontName = (__bridge NSString *)CGFontCopyPostScriptName(newFont); 
      CGDataProviderRelease(fontDataProvider); 
      CFErrorRef fonterror; 
      CTFontManagerRegisterGraphicsFont(newFont, &fonterror); 

      CGFontRelease(newFont); 

      UIFont * finalFont = [UIFont fontWithName:newFontName size:20.0f]; 

      [txt_UserName setFont:finalFont]; 
     }); 
    }); 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

Sample Code Here

que se verá como

enter image description here

Cuestiones relacionadas