1. 程式人生 > >UILabel改變行間距、字間距(swift)

UILabel改變行間距、字間距(swift)

有時候根據需求需要改變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()

}
趕快試一下吧!

}