我有几个带有多行文字的UILabel,但行间距比我想要的要大。有没有办法改变这个?
答案 0 :(得分:37)
嗨,这是一个迟到的回复,但它可以帮助某些行高度可以更改文本从普通文件更改为属性
答案 1 :(得分:2)
自iOS 6起,Apple将NSAttributedString
添加到UIKit
,从而可以使用NSParagraphStyle
更改行间距。
要从NIB实际更改please see souvickcse's answer.
答案 2 :(得分:0)
因为我讨厌在界面生成器中使用属性文本(我总是会遇到IB错误),所以此扩展允许您直接在界面生成器中将行高设置为UILabel
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
}
}