Change character spacing on UILabel within Interface Builder

前端 未结 13 2627
说谎
说谎 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:39

    Swift 3.2 & Interface builder

    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(NSKernAttributeName,
                                               value: newValue,
                                               range: NSRange(location: 0, length: attributedString.length))
    
                attributedText = attributedString
            }
    
            get {
                if let currentLetterSpace = attributedText?.attribute(NSKernAttributeName, at: 0, effectiveRange: .none) as? CGFloat {
                    return currentLetterSpace
                }
                else {
                    return 0
                }
            }
        }
    }
    

提交回复
热议问题