UITextField显示"可选("")"在输入之前

时间:2016-01-29 21:48:45

标签: swift uitextfield swift2 optional

我目前正在将我的iOS应用转换为Swift 2并遇到了这个问题。我有一个使用数字键盘的文本字段。当我切换到Swift 2时,当我输入一个数字时,假设为5,它将在文本字段中显示为Optional("")5。我很确定这是因为扩展中的某些内容。

extension GroupViewController: UITextFieldDelegate {
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        var shouldProcess = false
        var shouldMoveToNextField = false

        let insertStringLength = string.characters.count
        if insertStringLength == 0 {
            shouldProcess = true
        } else {
            if textField.text!.characters.count == 0 {
                shouldProcess = true
            }
        }

        if shouldProcess {
            var newString = textField.text

            if newString!.characters.count == 0 {
                newString = "\(newString)\(string)"
                shouldMoveToNextField = true
            } else {
                if insertStringLength > 0 {
                    newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
                } else {
                    newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: "")
                }
            }

            textField.text = newString!

            if shouldMoveToNextField {
                let nextResponder = textField.superview?.viewWithTag(textField.tag + 1)

                if let nextResponder = nextResponder {
                    nextResponder.becomeFirstResponder()
                } else {
                    dismissKeyboard()
                }
            }
        }
        return false
    }
}

1 个答案:

答案 0 :(得分:1)

在以下代码中:

 var newString = textField.text

            if newString!.characters.count == 0 {
                newString = "\(newString)\(string)"
                shouldMoveToNextField = true
            }

更改...

newString = "\(newString)\(string)"

于...

newString = "\(string)"