UITextField - 在编辑更改之前获取文本

时间:2017-05-30 02:52:43

标签: ios swift inheritance uitextfield uitextfielddelegate

我将文本字段设置为仅接受整数,但希望使用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 }
    }
}

0 个答案:

没有答案