Skip to content

Instantly share code, notes, and snippets.

@thecoolwinter
Last active February 10, 2022 18:28
Show Gist options
  • Save thecoolwinter/df3dbfccdb1cbe41cacf8c08e6be8786 to your computer and use it in GitHub Desktop.
Save thecoolwinter/df3dbfccdb1cbe41cacf8c08e6be8786 to your computer and use it in GitHub Desktop.
UITextField that automatically formats a percentage as a user types. It limits the input, and can return a value without any string formatting.
//
// PercentageField.swift
//
// Created by Khan Winter on 8/16/20.
//
import UIKit
class PercentageField: UITextField {
public var value: Double {
get {
let max = String(string.numbers)
let divider: Double = pow(Double(10), Double(2))
return abs(Double(max.numbers.integer) / divider) / 100
}
set(newVal) {
text = String(format: "%.2f", newVal * 100) + "%"
}
}
override func awakeFromNib() {
super.awakeFromNib()
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
keyboardType = .numberPad
text = "%"
editingChanged()
}
convenience init() {
self.init()
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
keyboardType = .numberPad
text = "%"
editingChanged()
}
@objc func editingChanged() {
if !string.contains("%") {
text?.removeLast()
}
let max = String(string.numbers)
let divider: Double = pow(Double(10), Double(2))
text = String(format: "%.2f", abs(Double(max.numbers.integer) / divider)) + "%"
self.value = abs(Double(max.numbers.integer) / divider) / 100
}
}
extension UITextField {
var string: String { return text ?? "" }
}
extension String {
var numbers: String { return components(separatedBy: CharacterSet(charactersIn: "0123456789").inverted).joined() }
var integer: Int { return Int(numbers) ?? 0 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment