Change character spacing on UILabel within Interface Builder

前端 未结 13 2649
说谎
说谎 2020-12-23 09:21

Is there anyway to change the character spacing (track) on UILabel text using Interface Builder? If not, is there a way to do it programmatically on an existing UILabel that

13条回答
  •  鱼传尺愫
    2020-12-23 09:44

    SWIFT 4 UILabel extension:

    import UIKit
    
    extension UILabel {
    
        @IBInspectable
        var letterSpace: CGFloat {
            set {
                let attributedString: NSMutableAttributedString!
                if let currentAttrString = attributedText {
                    attributedString = NSMutableAttributedString(attributedString: currentAttrString)
                } else {
                    attributedString = NSMutableAttributedString(string: text ?? "")
                    text = nil
                } 
                attributedString.addAttribute(NSAttributedString.Key.kern,
                                              value: newValue,
                                              range: NSRange(location: 0, length: attributedString.length))
                attributedText = attributedString
            }
    
            get {
                if let currentLetterSpace = attributedText?.attribute(NSAttributedString.Key.kern, at: 0, effectiveRange: .none) as? CGFloat {
                    return currentLetterSpace
                } else {
                    return 0
                }
            }
        }
    }
    

提交回复
热议问题