1

Im trying to give LineSpacing and LineHeight to my UILabel. I have an extension with two functions that both works individually. Cant get them to work together though.

extension UILabel {

func setText(text: String, lineSpacing: CGFloat) {
    self.attributedText = NSAttributedString(string: text, attributes: lineSpacingAttribute(lineSpacing))
}

func setText(text:String, CharacterSpacing:CGFloat) {

    let attributedString = NSMutableAttributedString(string: text)
    attributedString.addAttribute(NSKernAttributeName, value: CharacterSpacing, range: NSMakeRange(0, text.characters.count))
    self.attributedText = attributedString

 } 
}

The second function obviously overrides the first one when I do this:

    ExampleLabel.setText(myTextString, withLineSpacing: 10)
    ExampleLabel.setText(myTextString, CharacterSpacing: 10, lineSpacing: 10)

I've tried to merge these functions into one but I always end up with errors. Help please?

N.B
  • 139
  • 1
  • 5

1 Answers1

0

Here's a version of the setText function, adapted from the Swift answer at How do you use NSAttributedString? :

func setText(text:String, CharacterSpacing:CGFloat, lineSpacing: CGFloat) {
    let myParagraphStyle = NSMutableParagraphStyle()
    myParagraphStyle.lineSpacing = lineSpacing
    let myAttributes:Dictionary = [
        NSParagraphStyleAttributeName: myParagraphStyle,
        NSKernAttributeName: CharacterSpacing
    ]
    let attributedString = NSAttributedString(string: text, attributes: myAttributes)
    label1.attributedText = attributedString
}

and that seems to be working for me.

Community
  • 1
  • 1
emrys57
  • 6,679
  • 3
  • 39
  • 49