Skip to content

Instantly share code, notes, and snippets.

@vietstone-ng
Created June 14, 2017 07:08
Show Gist options
  • Save vietstone-ng/8baccf4c68f0083941a70414c9b8000f to your computer and use it in GitHub Desktop.
Save vietstone-ng/8baccf4c68f0083941a70414c9b8000f to your computer and use it in GitHub Desktop.
//
// SpacingButton.swift
// MglabSpice
//
// Created by Viet Nguyen Tran on 6/14/17.
// Copyright © 2017 iossimple. All rights reserved.
//
import UIKit
@IBDesignable
class SpacingButton: UIButton {
@IBInspectable var letterSpacing: CGFloat = 0 {
didSet {
updateSpacing()
}
}
override func setTitle(_ title: String?, for state: UIControlState) {
super.setTitle(title, for: state)
updateSpacing()
}
func updateSpacing() {
if let text = self.title(for: .normal), text.characters.count != 0 {
let attributedString = NSMutableAttributedString(string: text)
let range = NSMakeRange(0, text.characters.count)
// default attributes
if let font = self.titleLabel?.font {
attributedString.addAttribute(NSFontAttributeName, value: font, range: range)
}
if let color = self.titleColor(for: .normal) {
attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
// letter Spacing
if letterSpacing != 0 {
let letterSpacingRange = NSMakeRange(range.location, range.length - 1)
attributedString.addAttribute(NSKernAttributeName, value: letterSpacing, range: letterSpacingRange)
}
// show text on button
self.setAttributedTitle(attributedString, for: .normal)
} else {
self.setAttributedTitle(nil, for: .normal)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment