UILabel改变行间距、字间距(swift)

来源:互联网 发布:淘宝商城咨询电话 编辑:程序博客网 时间:2024/06/04 18:04

有时候根据需求需要改变label字与字或行与行之间间距大小,但系统并没有提供这样的方法,下面我对label写了一个延展来实现这一功能!

extension UILabel {

/**  改变行间距  */func changeLineSpace(space:CGFloat) {    if self.text == nil || self.text == "" {        return    }    let text = self.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())!))    self.attributedText = attributedString    self.sizeToFit()}/**  改变字间距  */func changeWordSpace(space:CGFloat) {    if self.text == nil || self.text == "" {        return    }    let text = self.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())!))    self.attributedText = attributedString    self.sizeToFit()}/**  改变字间距和行间距  */func changeSpace(lineSpace:CGFloat, wordSpace:CGFloat) {    if self.text == nil || self.text == "" {        return    }    let text = self.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())!))    self.attributedText = attributedString    self.sizeToFit()}赶快试一下吧!

}

0 0