Get UITableView to scroll to the selected UITextField and Avoid Being Hidden by Keyboard

后端 未结 13 978
鱼传尺愫
鱼传尺愫 2020-11-29 17:47

I have a UITextField in a table view on a UIViewController (not a UITableViewController). If the table view is on a UITableViewC

13条回答
  •  醉梦人生
    2020-11-29 18:31

    You need to resize the tableView itself so that it does not go under the keyboard.

    -(void) textFieldDidBeginEditing:(UITextField *)textField {
    
    // SUPPOSEDLY Scroll to the current text field
    self.worldsTableView.frame = CGRectMake(//make the tableView smaller; to only be in the area above the keyboard);
    CGRect textFieldRect = [textField frame];
    [self.wordsTableView scrollRectToVisible:textFieldRect animated:YES];
    
    }
    

    Alternatively, you can use a keyboard notification; this works slightly better because you have more information, and is more consistent in terms of knowing when the keyboard is coming up:

    //ViewDidLoad
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    

    And then implement:

    - (void)keyboardWillShow:(NSNotification *)notification {
    
    }
    - (void)keyboardWillHide:(NSNotification *)notification {
    
    }
    

提交回复
热议问题