UITableView with Keyboard handling for UITextFields

UITableView has its parent class as UIScrollView. So, if you have a UITableViewCell , which has UITextField, then it needs to handle the contentOffset.

More details on contentOffset (another url)and keyboard handling  in iOS.

Lets say if we want to add a bottom inset of 216 (approx. kyeboard height). the following would be the code
You basically change the content Offset while the content size remains the same.

self.contentOffset = UIEdgeInset(0,0,216,0).

This will move the content ( in the UITableView) up by 216.

The below code also handles autosuggestion bar ,  as the autosuggestion delta (approx. 29) gets added to existing delta. And Removes it accordingly.


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self registerNotifications:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self registerNotifications:NO];
}

-(void)registerNotifications:(BOOL)registerNotifications{
    if(registerBoardNotifications){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willShowKeyboard:) name:UIKeyboardWillShowNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willHideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    }else{
        [[NSNotificationCenter  defaultCenter] removeObserver:self];
    }
    
}

-(void)willShowKeyboard:(NSNotification*) notification{
    // Retrieve the keyboard begin / end frame values
    CGRect beginFrame = [[notification.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endFrame =  [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat delta = (beginFrame.origin.y - endFrame.origin.y);
    
    if(delta==0){
        return; //Nothing has changed so skip
    }

    NSLog(@"Delta = %f",delta); // Keyboard height offset , Auto - suggestion height
    UIEdgeInsets contentInsets = self.tableView.contentInset ;
    contentInsets.bottom += delta;
    [self.tableView setContentInset:contentInsets];
    
    [self.tableView setScrollIndicatorInsets:contentInsets];
    
    
}

-(void)willHideKeyboard:(NSNotification*) notification{
    [self.tableView setContentInset:UIEdgeInsetsZero];
    [self.tableView setScrollIndicatorInsets:UIEdgeInsetsZero];

}



Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

How to set Custom Section Header in UITableView for ios sdk version greater than 6