I have an application in Swift 1 for iPAD, I would like to remove or not accept the "." input. in my textField. It is like NumberPad. I found some solutions here but none in Swift.
I have an application in Swift 1 for iPAD, I would like to remove or not accept the "." input. in my textField. It is like NumberPad. I found some solutions here but none in Swift.
If you need to make a field for integer input you can simply subclass UITextField and customize your field within the awakeFromNib method and you can also add there addTarget to UIControlEvents .editingChanged and a method to filter the characters that do not be digits. Here is the response link that I have posted / updated in the OS in English:
import UIKit
class IntegerField: UITextField {
override func awakeFromNib() {
super.awakeFromNib()
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
keyboardType = .numberPad
textAlignment = .right
editingChanged()
}
func editingChanged() {
text = Formatter.decimal.string(from: string.numbers.integer as NSNumber)
}
}
struct Formatter {
static let decimal = NumberFormatter(numberStyle: .decimal)
}
extension UITextField {
var string: String { return text ?? "" }
}
extension String {
var numbers: String { return components(separatedBy: Numbers.characterSet.inverted).joined() }
var integer: Int { return Int(numbers) ?? 0 }
}
struct Numbers { static let characterSet = CharacterSet(charactersIn: "0123456789") }
extension NumberFormatter {
convenience init(numberStyle: NumberFormatter.Style) {
self.init()
self.numberStyle = numberStyle
}
}