lunes, 23 de mayo de 2016

iOS: Tex with various colors or formats

Objective C

- (NSAttributedString*)_text
{
    NSString* differentColorText = @"differentColorText";
    
    NSString* fullText = [NSString stringWithFormat:@"some text %@ some more text"differentColorText];
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:fullText];
    
    NSRange range = [fullText rangeOfString: differentColorText];
    
    [string addAttribute:NSForegroundColorAttributeName
                   value:[UIColor redColor]
                   range:range];

    [string addAttribute:NSFontAttributeName 
                   value:[UIFont boldSystemFontOfSize:12      
                   range: range];
    
    return string;


}

[self.label setAttributedText:[self _text]];

Swift


let text = "some text"
let fullText = "something else \(text)"
let range = (fullText as NSString).range(of: text)
        
let attributedText = NSMutableAttributedString(string: fullText)
attributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 17), range: range)
        

field.attributedText = attributedText

No hay comentarios:

Publicar un comentario