iPhone / iPad: ¿Cómo funciona exactamente utilizar NSAttributedString?
-
05-10-2019 - |
Pregunta
Sí, muchas personas están diciendo acerca de texto enriquecido en iPhone / iPad y muchos sabe acerca NSAttributedString
.
Sin embargo, el uso de NSAttributedString
? He buscado por mucho tiempo, no hay indicios de extracto de este.
Yo sé cómo configurar un NSAttributedString
, entonces, ¿qué debo hacer para mostrar un texto en el iPhone / iPad con texto enriquecido?
La documentación oficial dice que se debe utilizar con CoreText.Framework
, lo que quiere decir eso?
¿Hay alguna forma simple como esto?
NSAttributedString *str;
.....
UILabel *label;
label.attributedString = str;
Solución
Se debe echar un vistazo a de AliSoftware OHAttributedLabel . Es una subclase de UILabel que dibuja una NSAttributedString y también proporciona métodos de conveniencia para establecer los atributos de un NSAttributedString de clases UIKit.
A partir del ejemplo proporcionado en el repositorio:
#import "NSAttributedString+Attributes.h"
#import "OHAttributedLabel.h"
/**(1)** Build the NSAttributedString *******/
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"Hello World!"];
// for those calls we don't specify a range so it affects the whole string
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
// now we only change the color of "Hello"
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
/**(2)** Affect the NSAttributedString to the OHAttributedLabel *******/
myAttributedLabel.attributedText = attrStr;
// Use the "Justified" alignment
myAttributedLabel.textAlignment = UITextAlignmentJustify;
// "Hello World!" will be displayed in the label, justified, "Hello" in red and " World!" in gray.
Nota: En iOS 6+ puede hacer que las cadenas atribuidas mediante el attributedText propiedad de UILabel.
Otros consejos
A partir de la IOS 6.0 que puede hacerlo así:
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Hello. That is a test attributed string."];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(3,5)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(10,7)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];
label.attributedText = str;
Usted debe tratar TTTAttributedLabel . Es una gota en el reemplazo para UILabel que funciona con NSAttributedString y es suficiente para performant UITableViewCells.
¿Hay alguna manera simple como
NSAttributedString * str;
UILabel * etiqueta;
label.attributedString = str;
Casi. Sólo tiene que utilizar un CATextLayer. Tiene una propiedad string
que se puede establecer a un NSAttributedString.
Edit (noviembre de 2012):. Por supuesto, todo esto ha cambiado en iOS 6. En iOS 6, se puede hacer exactamente lo que pidió el PO - asignar una cadena con atributos directamente a attributedText
de una etiqueta ??p>
respuesta para UILabel atribuye alineación del texto en IOS 6: Utilice NSMutableAttributedString y añadir NSMutableParagraphStyle al atributo. Algo como esto:
NSString *str = @"Hello World!";
NSRange strRange = NSMakeRange(0, str.length);
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str];
NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setAlignment:NSTextAlignmentCenter];
[attributedStr addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:strRange];
myUILabel.attributedText = attributedStr;
pensé que sería útil dar un ejemplo de analizar una cadena HTML (simplificado), para crear un NSAttributedString.
No está completa - Sólo asas y etiquetas, para empezar, y no se molesta con cualquier tratamiento de errores - pero es de esperar también un ejemplo útil de cómo empezar con NSXMLParserDelegate .. .
@interface ExampleHTMLStringToAttributedString : NSObject<NSXMLParserDelegate>
+(NSAttributedString*) getAttributedStringForHTMLText:(NSString*)htmlText WithFontSize:(CGFloat)fontSize;
@end
@interface ExampleHTMLStringToAttributedString()
@property NSString *mpString;
@property NSMutableAttributedString *mpAttributedString;
@property CGFloat mfFontSize;
@property NSMutableString *appendThisString;
@property BOOL mbIsBold;
@property BOOL mbIsItalic;
@end
@implementation ExampleHTMLStringToAttributedString
@synthesize mpString;
@synthesize mfFontSize;
@synthesize mpAttributedString;
@synthesize appendThisString;
@synthesize mbIsBold;
@synthesize mbIsItalic;
+(NSAttributedString*) getAttributedStringForHTMLText:(NSString*)htmlText WithFontSize:(CGFloat)fontSize {
ExampleHTMLStringToAttributedString *me = [[ExampleHTMLStringToAttributedString alloc] initWithString:htmlText];
return [me getAttributedStringWithFontSize:fontSize];
}
- (id)initWithString:(NSString*)inString {
self = [super init];
if (self) {
if ([inString hasPrefix:@""]) {
mpString = inString;
} else {
mpString = [NSString stringWithFormat:@"%@", inString];
}
mpAttributedString = [NSMutableAttributedString new];
}
return self;
}
-(NSAttributedString*) getAttributedStringWithFontSize:(CGFloat)fontSize {
mfFontSize = fontSize;
// Parse the XML
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[mpString dataUsingEncoding:NSUTF8StringEncoding]];
parser.delegate = self;
if (![parser parse]) {
return nil;
}
return mpAttributedString;
}
-(void) appendTheAccumulatedText {
UIFont *theFont = nil;
if (mbIsBold && mbIsItalic) {
// http://stackoverflow.com/questions/1384181/italic-bold-and-underlined-font-on-iphone
theFont = [UIFont fontWithName:@"Helvetica-BoldOblique" size:mfFontSize];
} else if (mbIsBold) {
theFont = [UIFont boldSystemFontOfSize:mfFontSize];
} else if (mbIsItalic) {
theFont = [UIFont italicSystemFontOfSize:mfFontSize];
} else {
theFont = [UIFont systemFontOfSize:mfFontSize];
}
NSAttributedString *appendThisAttributedString =
[[NSAttributedString alloc]
initWithString:appendThisString
attributes:@{NSFontAttributeName : theFont}];
[mpAttributedString appendAttributedString:appendThisAttributedString];
[appendThisString setString:@""];
}
#pragma NSXMLParserDelegate delegate
-(void)parserDidStartDocument:(NSXMLParser *)parser{
appendThisString = [NSMutableString new];
mbIsBold = NO;
mbIsItalic = NO;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"body"]){
} else if ([elementName isEqualToString:@"i"]) {
[self appendTheAccumulatedText];
mbIsItalic = YES;
} else if ([elementName isEqualToString:@"b"]) {
[self appendTheAccumulatedText];
mbIsBold = YES;
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"body"]){
[self appendTheAccumulatedText];
} else if ([elementName isEqualToString:@"i"]) {
[self appendTheAccumulatedText];
mbIsItalic = NO;
} else if ([elementName isEqualToString:@"b"]) {
[self appendTheAccumulatedText];
mbIsBold = NO;
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[appendThisString appendString:string];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
}
@end
Para utilizar, hacer algo como esto:
self.myTextView.attributedText = [ExampleHTMLStringToAttributedString getAttributedStringForHTMLText:@"this is <b>bold</b> text" WithFontSize:self.myTextView.pointSize];
A partir de la IOS 6.0 que puede hacerlo así: otro código de ejemplo.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"This is my test code to test this label style is working or not on the text to show other user"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,31)];
[str addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(61,10)];
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:13.0] range:NSMakeRange(32, 28)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:13.0] range:NSMakeRange(65, 20)];
_textLabel.attributedText = str;
En Swift utilizar esto,
Esto hará que Titl los textos en negrita,
var title = NSMutableAttributedString(string: "Title Text")
title.addAttributes([NSFontAttributeName: UIFont(name: "AvenirNext-Bold", size: iCurrentFontSize)!], range: NSMakeRange(0, 4))
label.attributedText = title
Sé que es poco tarde, pero será útil para otros,
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:@"string" attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
[self.label setAttributedText:newString];
Añadir el atributo deseado para el diccionario y pasarlo como un parámetro de atributos