Tengo una cadena como "Esta es una buena manzana". para mostrar en mi UIlabel. Me gustaría establecer la palabra "bueno" con diferentes fuentes. Simplemente mire como "Esta es una buena apple".¿Es posible establecer una fuente diferente en One UIlabel?
Respuesta
Tome un vistazo a NSAttributedString ... Use OHAttributedLabel dibujar NSAttributedString porque UILabel, UITextView doesnot apoyo NSAttributedString ...
PD: si va a distribuir una nueva aplicación iOS 6 o, como UILabel ahora son compatibles con NSAttributedString, debe usar UILabel directamente en lugar de OHAttributedLabel, ya que ahora es compatible de forma nativa con el sistema operativo.
¡parece genial !, ¡thx! –
Aún no lo he probado, pero creo * esto es obsoleto a partir de iOS 6.0. El 'UILabel' original ahora tiene una propiedad' attributeText' - ver http://developer.apple.com/library/ios/documentation/uikit/reference/UILabel_Class/Reference/UILabel.html # // apple_ref/occ/instp/UILabel/attribuText –
@MarkAmery Tengo la actualización de mi otra respuesta, pero olvídate de actualizar esto. Gracias por notificar http://stackoverflow.com/questions/4208282/advance-search-implementation-in-iphone/4208329#4208329 – KingofBliss
Esto no es posible con UILabel. Pero podría usar Core Text.
Otro enfoque más fácil podría ser utilizar un UIWebView muy pequeño. En esto puede establecer la fuente usando comandos html.
Lo siento, pero eso no es posible con la aplicación UILabel, tiene dos opciones:
- Puede crear una UIWebView y poner el texto HTML formateado
- Usted puede hacer su propia aplicación UILabel con la funcionabilidad , con, por ejemplo, Core Text
En lugar de utilizar dos UILabels, puede tener una etiqueta con varios estilos y colores de fuentes de texto. Aquí está un ejemplo:
UILabel *customLbl = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 25)];
customLbl.backgroundColor = [UIColor yellowColor];
[self createTwoTextStyleInSingleUILabel:customLbl];// custom method calling
[self.view addSubview:customLbl];
método personalizado es el siguiente: Antes de aplicar este método, añadir marco QuartzCore (necesario para CALayers), y el marco CoreText (necesario para la cadena con atributos.) En su proyecto.
#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>
- (void)createTwoTextStyleInSingleUILabel: (UILabel *) myLabel{
NSString *firstText = NSLocalizedString(@"First text:", nil);
NSString *secondText = [NSString stringWithFormat:@"%@ %@",firstText,@"Second text"];
CATextLayer *myLabelTextLayer;
/* Create the text layer on demand */
if (!myLabelTextLayer) {
myLabelTextLayer = [[CATextLayer alloc] init];
myLabelTextLayer.backgroundColor = [UIColor clearColor].CGColor;
myLabelTextLayer.wrapped = NO;
CALayer *layer = myLabel.layer; //assign layer to your UILabel
myLabelTextLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30);
myLabelTextLayer.contentsScale = [[UIScreen mainScreen] scale];
myLabelTextLayer.alignmentMode = kCAAlignmentCenter;
[layer addSublayer:myLabelTextLayer];
}
/* Create the attributes (for the attributed string) */
// customizing first string
CGFloat fontSize = 16;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
CTFontRef ctBoldFont = CTFontCreateWithName((__bridge CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
CGColorRef cgColor = [UIColor redColor].CGColor;
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)ctBoldFont, (id)kCTFontAttributeName,
cgColor, (id)kCTForegroundColorAttributeName, nil];
CFRelease(ctBoldFont);
// customizing second string
UIFont *font = [UIFont systemFontOfSize:16];
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
CGColorRef cgSubColor = [UIColor blackColor].CGColor;
NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)ctFont, (id)kCTFontAttributeName,cgSubColor, (id)kCTForegroundColorAttributeName, nil];
CFRelease(ctFont);
/* Create the attributed string (text + attributes) */
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:secondText attributes:attributes];
float lengthOfSecondString = 12.0; // length of second string including blank space inbetween text, space in front , space after text.. Be careful, your app may crash here if length is beyond the second text length (lengthOfSecondString = text length + blank spaces)
[attrStr addAttributes:subAttributes range:NSMakeRange(firstText.length, lengthOfSecondString)];
// you can add another subattribute in the similar way as above , if you want change the third textstring style
/* Set the attributes string in the text layer :) */
myLabelTextLayer.string = attrStr;
myLabelTextLayer.opacity = 1.0; //to remove blurr effect
}
Comprobaré este código, realmente thx :) –
No es una manera de establecer diferentes fuentes Multiple/otros & propiedades en la etiqueta utilizando NSMutableAttributedString. Foll es mi código:
UIFont *ArialFont = [UIFont fontWithName:@"arial" size:18.0];
NSDictionary *arialdict = [NSDictionary dictionaryWithObject: ArialFont forKey:NSFontAttributeName];
NSMutableAttributedString *AattrString = [[NSMutableAttributedString alloc] initWithString:title attributes: arialdict];
UIFont *VerdanaFont = [UIFont fontWithName:@"verdana" size:12.0];
NSDictionary *veradnadict = [NSDictionary dictionaryWithObject:VerdanaFont forKey:NSFontAttributeName];
NSMutableAttributedString *VattrString = [[NSMutableAttributedString alloc]initWithString: newsDate attributes:veradnadict];
[VattrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:(NSMakeRange(0, 15))];
[AattrString appendAttributedString:VattrString];
lblText.attributedText = AattrString;
Tenga en cuenta que es la lblText UILabel, toma como propietario del archivo.
Uno puede seguir añadiendo tantos NSMutableAttributedString que quiere ..
También tenga en cuenta que he añadido verdana & fuente Arial en mi proyecto & añadió un plist para el mismo.
no funciona ... [NSDictionary dictionaryWithObject: ArialFont forKey: NSFontAttributeName] ; Obteniendo error en esta línea –
@RajeshPillai ¿Ha definido la fuente en la primera línea? UIFont * ArialFont = [UIFont fontWithName: @ "arial" size: 18.0]; – Akshay
Modified respuesta de Akshay e implementado con Swift:
// First part with font size 10
let firstPartInfo = [NSFontAttributeName: UIFont.systemFontOfSize(10.0)]
var attributedString = NSMutableAttributedString(string: "First Part", attributes: firstPartInfo)
// Second part with font size 20
let secondPartInfo = [NSFontAttributeName: UIFont.systemFontOfSize(20.0)]
attributedString.appendAttributedString(
NSAttributedString(string: "Second Part", attributes: secondPartInfo))
// Lastly set the attributed text
label.attributedText = attributedString
hay razón para usar soluciones de terceros o subclases.
- 1. ¿es posible establecer múltiples colores en UILabel?
- 2. Problemas con la configuración de una fuente diferente para UILabel
- 3. iTextSharp: ¿es posible establecer un color de fuente diferente para la misma celda y fila?
- 4. Opacidad diferente para UILabel y el texto de UILabel
- 5. ¿Es posible tener Liferay SDK en una ubicación diferente a la de los códigos fuente?
- 6. ¿Es posible establecer MasterType programáticamente?
- 7. ¿Es posible cambiar la fuente tooltip ToolStripMenuItem?
- 8. UILabel con fuente personalizada erróneamente renderizada
- 9. UILabel - configuración de fuente - tipo de letra programáticamente en iPhone
- 10. Es posible adjuntar UITapGestureRecognizer a la subclase UILabel
- 11. Configurando la fuente de UILabel con Interface Builder sale Helvetica
- 12. ¿Es posible establecer una URL base para la aplicación NodeJS?
- 13. ¿Es posible establecer una cookie manualmente usando sharedHTTPCookieStorage para UIWebView?
- 14. ¿Es posible establecer un objeto como nulo?
- 15. ¿Es posible establecer drawableLeft mediante programación?
- 16. establecer el número máximo de líneas en uilabel
- 17. establecer UIButton fuente
- 18. El código fuente es diferente de la versión original
- 19. ¿Es posible compilar programáticamente código fuente java solo en memoria?
- 20. Fuente diferente para todos los títulos en LaTeX
- 21. Animate UILabel no es liso
- 22. UILabel y fuentes
- 23. ¿Es posible establecer columna predeterminada en NewId() de SQL Server?
- 24. ¿Es posible establecer cabeceras HTTP personalizado en la vista Web
- 25. ¿Es posible establecer dinámicamente RequestMappings en Spring MVC?
- 26. El uso de una fuente personalizada con texto en negrita en un UILabel
- 27. ¿Es posible leer una cookie de un subdominio diferente? ¿Si es así, cómo?
- 28. Android - Cómo establecer una fuente personalizada para la aplicación entera
- 29. ¿Es posible establecer la afinidad con sched_setaffinity en Android?
- 30. ¿Es posible establecer la transparencia en CSS3 box-shadow?
Creé una clase fácil para hacer esto: http://past.is/NDe3 – AncAinu