在文本字段中分配和辞职第一响应者

时间:2017-04-28 08:22:47

标签: ios iphone swift3

我正在实现一个OTP功能,如此Auto Resign and assign first responder in text field in Swift所示,但在以下几行中出现错误,因为它们已被弃用于Swift 3

    let start = text!.startIndex.advancedBy(range.location)
    let end = start.advancedBy(range.length)

这是什么解决方法?

2 个答案:

答案 0 :(得分:0)

如果要实现otp功能。以下是您可以使用的代码。 每个文本字段都有标记,根据标记值,您可以轻松响应下一个文本字段。

extension YOUR_VC:UITextFieldDelegate{

func textFieldDidBeginEditing(_ textField: UITextField) {
 // to make text field empty    
 textField.text = ""
}


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if(string.length == 1){
        textField.text = string
        textField.resignFirstResponder();

    }
    return false
}

func textFieldDidEndEditing(_ textField: UITextField) {
    // for making next text field first responder after a character is entered in previous textfield
    switch textField.tag {
    case 1:
        otpTextTwo.becomeFirstResponder()
    case 2:
        otpTextThree.becomeFirstResponder()
    case 3:
        otpTextFour.becomeFirstResponder()
    case 4:
        otpTextFive.becomeFirstResponder()
    case 5:
        otpTextSix.becomeFirstResponder()
    case 6:

       // self.doneFecthingOtp()
    default:
        //print("NOt case")
    }
} }
希望这会有所帮助。

答案 1 :(得分:0)

你应该在swift3中这样写:

let start = text?.index((text?.startIndex)!, offsetBy: range.location)
let end = text?.index(start!, offsetBy: range.length)
let indexRange = text?[start! ..< end!]