检测是否在UITextField中键入了“空格”,并移动到下一个UITextField

时间:2016-03-07 19:19:35

标签: ios swift uitextfield

我是Swift的新手,我正在将一个小表单实现为一个解决方案。我有三个UITextFields,我想这样做,如果我输入一个单词,然后键入“空格键”,光标将移动到下一个UITextField(即它将阻止您在字段中键入多个单词) 。

如果我这样做,我该如何解决呢?

我以为我应该覆盖

textField(_:shouldChangeCharactersInRange:replacementString:)

方法 - 这是正确的吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

试试这个

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // Get your textFields text
    let str = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

    // Check if the last character is a space
    // If true then move to the next textfield
    if str.characters.last! == " "{
        print("SPACE!")
        textField2.becomeFirstResponder()
    }
    else{
        print(str.characters.last!)
    }

    return true
}

答案 1 :(得分:0)

试试这个,

@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var textField2: UITextField!
@IBOutlet weak var textField3: UITextField!

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let str = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

if str.characters.last! == " “{
        if textField == textField1{
            textField2.becomeFirstResponder()
        } else  if textField == textField2{
            textField3.becomeFirstResponder()
        } else  if textField == textField3{
                   // do what you want
            }
}
return true
}