当单击键盘中的返回键时,UITextField如何移动到下一个TextField

时间:2018-03-15 06:43:58

标签: swift uitextfield uitextfielddelegate

我正在使用此代码移动UITextField并且它正在工作,但我对这段代码不满意而且我想(当我点击返回键然后Cursor移动到下一个UITextField)这个函数在我的注册或登录表单中任何人都可以建议我

func textFieldDidBeginEditing(_ textField: UITextField) {
    switch textField {
    case txtFldSponsorID:
        moveTextfield(textfield: txtFldSponsorID, moveDistance: 0, up: true)
    case txtFldFullName:
        moveTextfield(textfield: txtFldFullName, moveDistance: -10, up: true)
    case txtFldEmail:
        moveTextfield(textfield: txtFldEmail, moveDistance: -10, up: true)
    case txtFldMobile:
        moveTextfield(textfield: txtFldMobile, moveDistance: -10, up: true)
    case txtFldAddress:
        moveTextfield(textfield: txtFldAddress, moveDistance: -80, up: true)
    case txtFldCity:
        moveTextfield(textfield: txtFldCity, moveDistance: -80, up: true)
    default:
        break
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    switch textField {
    case txtFldSponsorID:
        moveTextfield(textfield: txtFldSponsorID, moveDistance: 0, up: true)
    case txtFldFullName:
        moveTextfield(textfield: txtFldFullName, moveDistance: 10, up: true)
    case txtFldEmail:
        moveTextfield(textfield: txtFldEmail, moveDistance: 10, up: true)
    case txtFldMobile:
        moveTextfield(textfield: txtFldMobile, moveDistance: 10, up: true)
    case txtFldAddress:
        moveTextfield(textfield: txtFldAddress, moveDistance: 80, up: true)
    case txtFldCity:
        moveTextfield(textfield: txtFldCity, moveDistance: 80, up: true)
    default:
        break
    }
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

3 个答案:

答案 0 :(得分:3)

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        if textField == txtFldSponsorID {
            txtFldFullName.becomeFirstResponder()
        } else if textField == txtFldFullName {
            txtFldEmail.becomeFirstResponder()
        } else if textField == txtFldEmail {
            txtFldMobile.becomeFirstResponder()
        } else if textField == txtFldMobile {
            txtFldAddress.becomeFirstResponder()
        } else {
            txtFldCity.resignFirstResponder()
        }
        return true
    }

您可以使用上面的UITextField Delegate方法跳转到下一个UItextField。

答案 1 :(得分:0)

当用户在键盘上按下Next时,为了将光标自动移动到下一个数据输入字段,您需要从当前字段中resignFirstResponder并使用becomeFirstResponder将其分配给下一个字段

if self.emaillabel.isEqual(self.anotherTextField)
 {
    self.anotherTextField.becomeFirstResponder()
 }

答案 2 :(得分:0)

1-为storyboard中的每个textField标记一个标记号

2-实现textField委托功能:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    if textField.tag == 1 {    //say this is txtFldSponsorID
        txtFldFullName.becomeFirstResponder()
    }
    return true
}

3-将故事板中的返回键类型更改为“next”而不是“return”,或使用代码:

txtFldSponsorID.returnKeyType = .next

4-不要忘记设置delegate = self