Change character spacing on UILabel within Interface Builder

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

    Try this. It will add the character spacing you assign, either you set simple text or attributed text.

    open class UHBCustomLabel : UILabel {
        @IBInspectable open var characterSpacing:CGFloat = 1 {
            didSet {
                updateWithSpacing()
            }
    
        }
    
        open override var text: String? {
            set {
                super.text = newValue
                updateWithSpacing()
            }
            get {
                return super.text
            }
        }
        open override var attributedText: NSAttributedString? {
            set {
                super.attributedText = newValue
                updateWithSpacing()     
            }
            get {
                return super.attributedText
            }
        }
        func updateWithSpacing() {
            let attributedString = self.attributedText == nil ? NSMutableAttributedString(string: self.text ?? "") : NSMutableAttributedString(attributedString: attributedText!)
            attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
            super.attributedText = attributedString
        }
    }
    

提交回复
热议问题