Not able to set textfield as becomeFirstResponder() with textfield outlet collection in tvos

295 views Asked by At

I took text field outlet collection and bind six text field over there. I want to becomeFirstResponder of next text field which is in text field outlet collection. I gave textfields tag 0 to 5 from storyboard. see,

Main ViewController:

class ViewController: UIViewController {

    @IBOutlet var txtSignUp: [UITextField]!
    var arrayPlaceHolder:NSArray!

    override func viewDidLoad() {
        super.viewDidLoad()

        arrayPlaceHolder = NSArray(array: ["1","2","3","4","5","6"])
        self.setTextFieldValue()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    private func setTextFieldValue(){

        for txtField in txtSignUp{
            let tagTxt = txtField.tag
            txtField.attributedPlaceholder = NSAttributedString(string:arrayPlaceHolder[tagTxt] as! String, attributes:[NSForegroundColorAttributeName:UIColor.black])
            if(tagTxt != ((arrayPlaceHolder.count) - 1)){
                txtField.returnKeyType = .next
            }
            txtField.delegate = self
        }
    }

}

extension ViewController:UITextFieldDelegate{

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

        textField.resignFirstResponder()

            for txt in txtSignUp{
                let nextTxt = (textField.tag + 1)
                if txt.tag == nextTxt {
                    txt.becomeFirstResponder()
                    break
                }
            }
            return true
        }
}

Error:

whose view is not in the window hierarchy!

Explanation:

In this code, I am not able to become next text field as becomeFirstResponder.

Can anyone help me to resolve this issue.

1

There are 1 answers

0
CloudInSky On

On TVos you have to use the textFieldDidEndEditing function because textFieldShouldReturn won't work to set the next responder:

class MyViewController: UIViewController{
    @IBOutlet weak var firstTextField: UITextField!
    @IBOutlet weak var secondTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        firstTextField.delegate = self
        secondTextField.delegate = self
        firstTextField.tag = 0
        secondTextField.tag = 1
    }
}
extension MyViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        if (textField.tag == 0){
            secondTextField.becomeFirstResponder()
        }
    }
}