UILabel改变⾏间距、字间距(swift)
有时候根据需求需要改变label字与字或⾏与⾏之间间距⼤⼩,但系统并没有提供这样的⽅法,下⾯我对label写了⼀个延展来实现这⼀功能!
extension UILabel {
/** 改变⾏间距 */
func changeLineSpace(space:CGFloat) {
== nil || lf.text == "" {
return
}
let text = lf.text
let attributedString = NSMutableAttributedString.init(string: text!)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = space
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: .init(location: 0, length: (text?.length())!))
lf.attributedText = attributedString
lf.sizeToFit()
}
/** 改变字间距 */
func changeWordSpace(space:CGFloat) {
== nil || lf.text == "" {
return
}
let text = lf.text
let attributedString = NSMutableAttributedString.init(string: text!, attributes: [NSKernAttributeName:space])
let paragraphStyle = NSMutableParagraphStyle()
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: .init(location: 0, length: (text?.length())!))
lf.attributedText = attributedString
lf.sizeToFit()
}
/** 改变字间距和⾏间距 */
func changeSpace(lineSpace:CGFloat, wordSpace:CGFloat) {
== nil || lf.text == "" {
return
}
let text = lf.text
let attributedString = NSMutableAttributedString.init(string: text!, attributes: [NSKernAttributeName:wordSpace])
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpace
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: .init(location: 0, length: (text?.length())!))
lf.attributedText = attributedString
lf.sizeToFit()
}
赶快试⼀下吧!
}