I've got several UILabels with multiple lines of text, but the line spacing is larger than I would prefer. Is there any way to change this?
Xcode: Is there a way to change line spacing (UI Label) in interface builder?
Asked Answered
Since iOS 6, Apple added NSAttributedString
to UIKit
, making it possible to use NSParagraphStyle
to change the line spacing.
To actually change it from NIB, please see souvickcse's answer.
Hi... Thanks.. What is the default value of the line spacing for the UILabel ? Thanks in advance.. –
Willie
The answer provided below is the correct answer for this –
Santiago
hi this is a late reply but it may help some one line height can be change change the text from plain to attribute
@Jaenicke This is not work for Custom font still now. –
Euripides
it works well, you just need to set the label height number to 0 –
Geniagenial
Since iOS 6, Apple added NSAttributedString
to UIKit
, making it possible to use NSParagraphStyle
to change the line spacing.
To actually change it from NIB, please see souvickcse's answer.
Hi... Thanks.. What is the default value of the line spacing for the UILabel ? Thanks in advance.. –
Willie
The answer provided below is the correct answer for this –
Santiago
Because I friggin hate using attributed text in interface builder (I always run into IB bugs), here is an extension to allow you to set line height multiple directly to a UILabel in interface builder
extension UILabel {
@IBInspectable
var lineHeightMultiple: CGFloat {
set{
//get our existing style or make a new one
let paragraphStyle: NSMutableParagraphStyle
if let existingStyle = attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: .none) as? NSParagraphStyle, let mutableCopy = existingStyle.mutableCopy() as? NSMutableParagraphStyle {
paragraphStyle = mutableCopy
} else {
paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.alignment = self.textAlignment
}
paragraphStyle.lineHeightMultiple = newValue
//set our text from existing text
let attrString = NSMutableAttributedString()
if let text = self.text {
attrString.append( NSMutableAttributedString(string: text))
attrString.addAttribute(NSAttributedString.Key.font, value: self.font, range: NSMakeRange(0, attrString.length))
}
else if let attributedText = self.attributedText {
attrString.append( attributedText)
}
//add our attributes and set the new text
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
get {
if let paragraphStyle = attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: .none) as? NSParagraphStyle {
return paragraphStyle.lineHeightMultiple
}
return 0
}
}
© 2022 - 2024 — McMap. All rights reserved.