Why UITextField becomeFirstResponder returns NO?

前端 未结 5 905
南笙
南笙 2021-01-18 06:48

This is my code:

while (true) {
    if ([identificationField becomeFirstResponder]) {

        NSLog(@\"finally!\");
        break;
    }
    else{
        i         


        
相关标签:
5条回答
  • 2021-01-18 07:27

    Whatever is already the first responder can refuse to give up first responder status. In that case, your UITextField won't become the first responder. So you should make sure that whatever is already the first responder isn't refusing to give up that status.

    EDIT:

    You won't want to leave this in an app when submitted to the app store, but here's some code that uses a private API to determine the current first responder:

    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView   *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
    

    You can use that to see what the first responder is, and that may help you find out why you can't get it to resign, if that's indeed the problem.

    0 讨论(0)
  • 2021-01-18 07:28

    Is your identificationField in UIView hierarchy? If it hasn't added into window and shown it cannot became first responder.

    0 讨论(0)
  • The call to canBecomeFirstResponder only checks if the receiver can itself become the first responder.

    The call to becomeFirstResponder will fail and return NO if either the receiver can't become first responder or if the current first responder can't resign.

    0 讨论(0)
  • 2021-01-18 07:42

    A UITextField will also refuse to become first responder if its userInteractionEnabled property is NO as I just discovered. I had to explicitly re-enable user interaction on the text field before it would accept first responder status.

    Also worth noting is you can force whatever element currently has first responder status to give it up by calling [UIView endEditing:YES] on any superview that contains the current first responder.

    0 讨论(0)
  • 2021-01-18 07:45

    You probably have another element that is stopping it. Need to know more about your project to really answer with the exact problem.

    However, here's a possible you have another textField that has the delegate method

    - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return NO;
    }
    

    That would mean it doesn't resign first responder.

    0 讨论(0)
提交回复
热议问题