Change character spacing on UILabel within Interface Builder

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

    Programming approach. (Try this, it should work for you)
    Note: I tested in Swift 4

    let label = UILabel()
    let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
    let attrString = NSMutableAttributedString(string: stringValue)
    var style = NSMutableParagraphStyle()
    style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
    style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
    
    // Line spacing attribute
    attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
    
    // Character spacing attribute
    attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
    
    label.attributedText = attrString
    

提交回复
热议问题