我试图将LineSpacing和LineHeight提供给我的UILabel。我有一个扩展,有两个功能,都可以单独工作。不能让他们一起工作。
extension UILabel {
func setText(text: String, lineSpacing: CGFloat) {
self.attributedText = NSAttributedString(string: text, attributes: lineSpacingAttribute(lineSpacing))
}
func setText(text:String, CharacterSpacing:CGFloat) {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSKernAttributeName, value: CharacterSpacing, range: NSMakeRange(0, text.characters.count))
self.attributedText = attributedString
}
}
当我这样做时,第二个功能显然会覆盖第一个功能:
ExampleLabel.setText(myTextString, withLineSpacing: 10)
ExampleLabel.setText(myTextString, CharacterSpacing: 10, lineSpacing: 10)
我尝试将这些功能合并为一个,但我总是遇到错误。请帮忙?
答案 0 :(得分:0)
这是setText函数的一个版本,改编自How do you use NSAttributedString?的Swift答案:
func setText(text:String, CharacterSpacing:CGFloat, lineSpacing: CGFloat) {
let myParagraphStyle = NSMutableParagraphStyle()
myParagraphStyle.lineSpacing = lineSpacing
let myAttributes:Dictionary = [
NSParagraphStyleAttributeName: myParagraphStyle,
NSKernAttributeName: CharacterSpacing
]
let attributedString = NSAttributedString(string: text, attributes: myAttributes)
label1.attributedText = attributedString
}
这似乎对我有用。