Change character spacing on UILabel within Interface Builder

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

    Here is a solution for Swift 4 that won't override existing text attributes:

    extension UILabel {
    
        /**
         Add kerning to a UILabel's existing `attributedText`
         - note: If `UILabel.attributedText` has not been set, the `UILabel.text`
         value will be returned from `attributedText` by default
         - note: This method must be called each time `UILabel.text` or
         `UILabel.attributedText` has been set
         - parameter kernValue: The value of the kerning to add
         */
        func addKern(_ kernValue: CGFloat) {
            guard let attributedText = attributedText,
                attributedText.string.count > 0,
                let fullRange = attributedText.string.range(of: attributedText.string) else {
                    return
            }
            let updatedText = NSMutableAttributedString(attributedString: attributedText)
            updatedText.addAttributes([
                .kern: kernValue
                ], range: NSRange(fullRange, in: attributedText.string))
            self.attributedText = updatedText
        }
    }
    

提交回复
热议问题