Establecer espaciado de línea UILabel
¿Cómo puedo modificar el espacio entre líneas (interlineado) en una multilínea UILabel
?
10 answers
Editar: Evidentemente NSAttributedString
lo hará, en iOS 6 y posteriores. En lugar de usar un NSString
para establecer el texto de la etiqueta, cree un NSAttributedString
, establezca atributos en él, luego establézcalo como el .attributedText
en la etiqueta. El código que quieres será algo como esto:
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;
El antiguo attributedStringWithString de NSAttributedString hizo lo mismo, pero ahora ese está en desuso.
Por razones históricas, aquí está mi respuesta original: {[16]]}
Respuesta Corta: usted para cambiar el espaciado entre líneas de texto, tendrá que subclase UILabel
y rodar su propio drawTextInRect
, crear varias etiquetas o usar una fuente diferente (tal vez una editada para una altura de línea específica, consulte la respuesta de Phillipe).
Respuesta larga: En el mundo impreso y en línea, el espacio entre líneas de texto se conoce como "leading" (rima con "heading", y proviene del metal de plomo utilizado hace décadas). Leading es una propiedad de solo lectura de UIFont
, que fue obsoleta en 4.0 y sustituido por lineHeight
. Por lo que sé, no hay forma de crear una fuente con un conjunto específico de parámetros como lineHeight
; obtienes las fuentes del sistema y cualquier fuente personalizada que agregues, pero no puedes modificarlas una vez instaladas.
Tampoco hay un parámetro de espaciado en UILabel
.
No estoy particularmente contento con el comportamiento de UILabel
tal como está, así que sugiero escribir su propia subclase o usar una biblioteca de terceros. Eso hará que el comportamiento sea independiente de su elección de fuente y será el más reutilizable solución.
Desearía que hubiera más flexibilidad en UILabel
, ¡y estaría feliz de que me demostraran que estaba equivocado!
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-03-04 04:34:03
A partir de ios 6 puede establecer una cadena atribuida en la etiqueta UILabel:
NSString *labelText = @"some text";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:40];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
cell.label.attributedText = attributedString ;
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-09-30 07:26:52
Puede controlar el espaciado entre líneas en el storyboard:
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-05-23 10:31:37
Mi solución fue parchear el propio archivo de fuente y fijar definitivamente su altura de línea. http://mbauman.net/geek/2009/03/15/minor-truetype-font-editing-on-a-mac /
Tuve que modificar 'lineGap', 'ascender', 'descender' en el bloque 'hhea' (como en el ejemplo del blog).
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
2012-05-22 13:23:40
Desde el creador de interfaces:
Programáticamente:
SWift 4
Usando la extensión de etiqueta
extension UILabel {
func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {
guard let labelText = self.text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = lineHeightMultiple
let attributedString:NSMutableAttributedString
if let labelattributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Line spacing attribute
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
Ahora llama a la función de extensión
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) . // try values 1.0 to 5.0
// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0
O usando la instancia label (Simplemente copie y ejecute este código para ver el resultado)
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
Swift 3
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
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-10-26 10:23:37
Este tipo creó una clase para obtener la altura de la línea (sin usar CoreText, como biblioteca MTLabel): https://github.com/LemonCake/MSLabel
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
2012-05-16 12:04:44
Lo mejor que encontré es: https://github.com/mattt/TTTAttributedLabel
Es una subclase UILabel, así que simplemente puedes soltarla y luego cambiar la altura de la línea:
myLabel.lineHeightMultiple = 0.85;
myLabel.leading = 2;
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-06-26 13:45:25
He encontrado Bibliotecas de terceros Como esta:
Https://github.com/Tuszy/MTLabel
Para ser la solución más fácil.
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
2011-09-15 08:48:54
Aquí hay un código swift para que establezca el espaciado entre líneas mediante programación
let label = UILabel()
let attributedText = NSMutableAttributedString(string: "Your string")
let paragraphStyle = NSMutableParagraphStyle()
//SET THIS:
paragraphStyle.lineSpacing = 4
//OR SET THIS:
paragraphStyle.lineHeightMultiple = 4
//Or set both :)
let range = NSMakeRange(0, attributedText.length)
attributedText.addAttributes([NSParagraphStyleAttributeName : paragraphStyle], range: range)
label.attributedText = attributedText
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-02-14 13:44:29
Por supuesto, la respuesta de Mike no funciona si pasas la cadena programáticamente. En este caso es necesario pasar una cadena atribuida y cambiar su estilo.
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"Your \nregular \nstring"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:4];
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, attrString.length)];
_label.attributedText = attrString;
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-24 21:43:24