我有几个带有多行文本的 UILabel,但行距比我希望的要大。有什么办法可以改变这个吗?
问问题
11209 次
3 回答
46
hi this is a late reply but it may help some one line height can be change change the text from plain to attribute
于 2013-10-23T10:30:55.660 回答
2
从 iOS 6 开始,Apple 加入NSAttributedString
了UIKit
,使得可以NSParagraphStyle
用来改变行距。
要真正从 NIB 更改它,请参阅 souvickcse 的答案。
于 2012-08-24T16:19:12.627 回答
1
因为我讨厌在界面构建器中使用属性文本(我总是遇到 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
}
}
于 2019-02-01T17:01:12.153 回答