【发布时间】:2012-08-20 05:02:39
【问题描述】:
我有几个带有多行文本的 UILabel,但行距比我希望的要大。有什么办法可以改变这个吗?
【问题讨论】:
标签: xcode cocoa-touch interface-builder uilabel
我有几个带有多行文本的 UILabel,但行距比我希望的要大。有什么办法可以改变这个吗?
【问题讨论】:
标签: xcode cocoa-touch interface-builder uilabel
你好,这是一个迟到的回复,但它可能有助于一些行高可以改变,将文本从纯文本更改为属性
【讨论】:
从 iOS 6 开始,Apple 将 NSAttributedString 添加到 UIKit,使得使用 NSParagraphStyle 更改行距成为可能。
要真正从 NIB 更改它,please see souvickcse's answer.
【讨论】:
因为我讨厌在界面构建器中使用属性文本(我总是遇到 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
}
}
【讨论】: