Pages

Scroll UITextField above Keyboard in a UITableView OR UIScrollView in Swift and Objective C

In Objective C

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    CGPoint pointInTable = [textField.superview convertPoint:textField.frame.origin toView:_tableview];
    CGPoint contentOffset = _tableview.contentOffset;
   
    contentOffset.y = (pointInTable.y - textField.inputAccessoryView.frame.size.height);
   
    NSLog(@"contentOffset is: %@", NSStringFromCGPoint(contentOffset));   
    [_tableview setContentOffset:contentOffset animated:YES];   
    return YES;
}


-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];   
    if ([textField.superview.superview isKindOfClass:[UITableViewCell class]])
    {
        CGPoint buttonPosition = [textField convertPoint:CGPointZero
                                                  toView: _tableview];
        NSIndexPath *indexPath = [_tableview indexPathForRowAtPoint:buttonPosition];
       
        [_tableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:TRUE];
    }
   
    return YES;
}


 In Swift


 func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        var pointInTable:CGPoint = textField.superview!.convertPoint(textField.frame.origin, toView:_tableview)
        var contentOffset:CGPoint = _tableview.contentOffset
        contentOffset.y  = pointInTable.y
        if let accessoryView = textField.inputAccessoryView {
            contentOffset.y -= accessoryView.frame.size.height
        }
        _tableview.contentOffset = contentOffset
        return true;
    }