我将文本字段设置为仅接受整数,但希望使用UITextField继承而不是shouldChangeCharactersInRange
的委托。
有没有办法在调用editingChanged
之前获取文本值,因为如果输入的字符不在最后位置,使用dropLast()
将无法工作。
class TextFieldInteger: UITextField {
// A character set with number digits only
let decimalRange = CharacterSet.decimalDigits
override func awakeFromNib() {
self.addTarget(self, action: #selector(editingDidBegin), for: .editingDidBegin)
self.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
func editingDidBegin() {
// Remove all existing "," from the input if having any
input = input.replacingOccurrences(of: ",", with: "")
}
func editingChanged() {
if input.characters.count > 0 {
let textSet = CharacterSet(charactersIn: input)
if !decimalRange.isSuperset(of: textSet) {
input.dropLast()
}
}
}
}
extension UITextField {
var input: String {
get { return text ?? "" }
set { text = newValue }
}
}