Change character spacing on UILabel within Interface Builder

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

    I know it's not an Interface Builder solution, but you can create a UILabel extension and then add spacing to any UILabel you want:

    extension UILabel {
      func addCharacterSpacing(kernValue: Double = 1.15) {
        if let labelText = text, labelText.count > 0 {
          let attributedString = NSMutableAttributedString(string: labelText)
          attributedString.addAttribute(NSAttributedStringKey.kern, value: kernValue, range: NSRange(location: 0, length: attributedString.length - 1))
          attributedText = attributedString
        }
      }
    }
    

    Consider changing the default kernValue from 1.15 to something that works better with your design.


    When implementing always add character spacing after setting the text value:

    myLabel.text = "We used to be so close"
    myLabel.addCharacterSpacing()
    

    If you plan to have different spacing at different places in the app, you can override the default kern value:

    myLabelWithSpecialNeeds.addCharacterSpacing(kernValue: 1.3)
    

    This solution overrides any other attributes you might have on your UILabel's attributedText.

提交回复
热议问题