Skip to content

Instantly share code, notes, and snippets.

@damienlaughton
Last active April 30, 2018 12:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damienlaughton/f75a72c42f465b42e71891e6f643a6bb to your computer and use it in GitHub Desktop.
Save damienlaughton/f75a72c42f465b42e71891e6f643a6bb to your computer and use it in GitHub Desktop.
//
// UIKerningTextField.swift
// UIKerningTextField
//
// Created by Damien Laughton
// Copyright © 2018 Mobilology Limited. No rights reserved.
//
import UIKit
@IBDesignable class UIKerningTextField : UITextField {
@IBInspectable var kerningValue : CGFloat = 3.0 {
didSet {
self.configureAttributedText()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
didLoad()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didLoad()
}
override public var text: String? {
didSet {
self.configureAttributedText()
}
}
func didLoad() {
self.addTarget(self, action: #selector(UIKerningTextField.configureAttributedText as (UIKerningTextField) -> () -> ()), for: .editingChanged)
self.addTarget(self, action: #selector(UIKerningTextField.configureAttributedText as (UIKerningTextField) -> () -> ()), for: .valueChanged)
}
@objc func configureAttributedText () {
let text: String = self.attributedText?.string ?? self.text ?? ""
let fontSize = self.font?.pointSize ?? 13.0
let fontName = self.font?.fontName ?? UIFont.systemFont(ofSize: fontSize).fontName
let fontColor = self.textColor ?? UIColor.black
let font = UIFont(name: fontName, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
let attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.kern:self.kerningValue, NSAttributedStringKey.font:font, NSAttributedStringKey.foregroundColor:fontColor])
self.attributedText = attributedText
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment