Ejemplo de NSAttributedString con dos tamaños de fuente diferentes?


NSAttributedString es realmente impenetrable para mí.

Quiero establecer un UILabel para tener texto de diferentes tamaños, y deduzco que NSAttributedString es el camino a seguir, pero no puedo llegar a ninguna parte con la documentación sobre esto.

Me encantaría que alguien pudiera ayudarme con un ejemplo concreto.

Por ejemplo, digamos que el texto que quería era:

(in small letters:) "Presenting The Great..."
(in huge letters:) "HULK HOGAN!"

¿Puede alguien mostrarme cómo hacer eso? O incluso, una referencia que es simple y simple donde podría aprender por mí mismo? Te juro que lo he intentado. para entender esto a través de la documentación, e incluso a través de otros ejemplos en Stack Overflow, y simplemente no lo estoy entendiendo.

Author: Marcus Adams, 2013-08-21

4 answers

Usted haría algo como esto {

NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"];
[hogan addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:20.0]
              range:NSMakeRange(24, 11)];

Esto establecerá las dos últimas palabras en texto de 20 puntos; el resto de la cadena utilizará el valor predeterminado (que creo que es 12 puntos). Lo que podría ser confuso acerca de establecer el tamaño del texto es que tiene que establecer el tipo de letra y el tamaño al mismo tiempo-cada objeto UIFont encapsula ambas propiedades.

 157
Author: bdesham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-21 19:18:36

Solución Swift 3

Además, puede usar la función append en lugar de especificar índices en ObjC o Swift:

let attrString = NSMutableAttributedString(string: "Presenting The Great...",
                                           attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: 20) ])

attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",
                                            attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 40) ]))
 17
Author: iljn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 09:15:14

Solución Swift 4:

let attrString = NSMutableAttributedString(string: "Presenting The Great...",
                                       attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)]));

attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",
                                        attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 36)]));
 8
Author: Kunal Shah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 22:57:36

Si quieres hacerlo de la manera fácil, hay un repositorio de git llamado OHAttributedLabel que uso que proporciona una categoría en NSAttributedString. Te permite hacer cosas como:

NSMutableAttributedString *mystring = [[NSMutableAttributedString alloc] initWithString:@"My String"];
[mystring setTextColor:[UIColor colorWithRGB:78 green:111 blue:32 alpha:1]];
mystring.font = [UIFont systemFontOfSize:14];

Si no quieres usar una lib de terceros, echa un vistazo a este enlace para un tutorial decente sobre cómo comenzar con cadenas atribuidas.

 0
Author: JonahGabriel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-21 19:17:01