Skip to content

Instantly share code, notes, and snippets.

@phynet
Last active March 10, 2022 09:15
Show Gist options
  • Save phynet/ef86adef104c34f7bd09 to your computer and use it in GitHub Desktop.
Save phynet/ef86adef104c34f7bd09 to your computer and use it in GitHub Desktop.
Setting spaces between characters with Swift

##Setting spaces between characters with Swift (iOS)

###UIButton

    @IBOutlet weak var button: UIButton!

    button.titleLabel?.attributedText = NSAttributedString(string: string, attributes:[ NSKernAttributeName: 1.3])

###UILabel

    @IBOutlet weak var nameUser: UILabel!
    nameUser.attributedText = NSAttributedString(string: string,attributes:[ NSKernAttributeName: 1.3])

##Using an Extension

    extension UILabel {
  
      func attributeMyLabel(text: String) -> NSAttributedString{
        self.attributedText = NSAttributedString(string: text, attributes:[NSKernAttributeName: 1.3])
        return self.attributedText
      }
  
    //I've used a function, but this can be transformed into a var
    
      func attributeMyLabelSelfText() -> NSAttributedString{
        self.attributedText = NSAttributedString(string: self.text!, attributes:[NSKernAttributeName: 1.3])
        return self.attributedText
      }
    }

Use

    //Option 1 passing an argument
    @IBOutlet weak var lastName: UILabel!
    var lastname = kUserLastName //whatever string
    lastName.attributeMyLabel(lastname)
    
    //Option 2 using self text
    "headerTitle1".attributeMyLabelSelfText()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment