获取UITableView以滚动到所选的UITextField并避免被键盘隐藏

时间:2011-03-10 20:31:55

标签: xcode uitableview keyboard uitextfield

我在UITextField(不是UIViewController)的表格视图中有一个UITableViewController。 如果表格视图位于UITableViewController上,则表格将自动滚动到正在编辑的textField,以防止它被键盘隐藏。但是在UIViewController它没有。

我已经尝试了几天阅读多种方法来尝试实现这一目标,但我无法让它发挥作用。实际滚动的最接近的是:

-(void) textFieldDidBeginEditing:(UITextField *)textField {

// SUPPOSEDLY Scroll to the current text field

CGRect textFieldRect = [textField frame];
[self.wordsTableView scrollRectToVisible:textFieldRect animated:YES];

}

但是,这只会将表格滚动到最上面一行。 看似简单的任务已经过了几天的挫折。

我使用以下命令构造tableView单元格:

- (UITableViewCell *)tableView:(UITableView *)aTableView
    cellForRowAtIndexPath:(NSIndexPath *)indexPath {

NSString *identifier = [NSString stringWithFormat: @"%d:%d", [indexPath indexAtPosition: 0], [indexPath indexAtPosition:1]];

UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] 
        initWithStyle:UITableViewCellStyleDefault 
        reuseIdentifier:identifier] autorelease];

        cell.accessoryType = UITableViewCellAccessoryNone;

        UITextField *theTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 10, 130, 25)];

        theTextField.adjustsFontSizeToFitWidth = YES;
        theTextField.textColor = [UIColor redColor];
        theTextField.text = [textFieldArray objectAtIndex:indexPath.row];
        theTextField.keyboardType = UIKeyboardTypeDefault;
        theTextField.returnKeyType = UIReturnKeyDone;
        theTextField.font = [UIFont boldSystemFontOfSize:14];
        theTextField.backgroundColor = [UIColor whiteColor];
        theTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        theTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
        theTextField.clearsOnBeginEditing = NO;
        theTextField.textAlignment = UITextAlignmentLeft;

        //theTextField.tag = 0;
        theTextField.tag=indexPath.row;

        theTextField.delegate = self;

        theTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [theTextField setEnabled: YES];

        [cell addSubview:theTextField];

        [theTextField release];


}

return cell;
}

我怀疑如果我能以某种方式通过indexPath.row方法中的textFieldDidBeginEditing,我可以让tableView正确滚动吗?

感谢任何帮助。

13 个答案:

答案 0 :(得分:108)

在我的应用中,我已成功使用contentInsetscrollToRowAtIndexPath的组合,如下所示:

当您想要显示键盘时,只需在底部添加一个contentInset,其中您的表格具有所需的高度:

tableView.contentInset =  UIEdgeInsetsMake(0, 0, height, 0);

然后,您可以安全地使用

[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:cell_index inSection:cell_section] animated:YES];

通过添加contentInset,即使您专注于最后一个单元格,tableView仍然可以滚动。只需确保在解除键盘时重置contentInset。

修改
如果您只有一个部分(可以将cell_section替换为0)并使用textView标记来通知单元格行。

选中Scroll UITextField above Keyboard in a UITableView OR UIScrollView

答案 1 :(得分:46)

- (void)keyboardWillShow:(NSNotification *)sender
{
    CGFloat height = [[sender.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    NSTimeInterval duration = [[sender.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationOptions curveOption = [[sender.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16;

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|curveOption animations:^{
        UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, height, 0);
        tableView.contentInset = edgeInsets;
        tableView.scrollIndicatorInsets = edgeInsets;
    } completion:nil];
}

- (void)keyboardWillHide:(NSNotification *)sender
{
    NSTimeInterval duration = [[sender.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationOptions curveOption = [[sender.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue] << 16;

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|curveOption animations:^{
        UIEdgeInsets edgeInsets = UIEdgeInsetsZero;
        tableView.contentInset = edgeInsets;
        tableView.scrollIndicatorInsets = edgeInsets;
    } completion:nil];
}

并在 - (void)viewDidLoad

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

然后

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

答案 2 :(得分:10)

这是对FunkyKat答案的一个调整(非常感谢FunkyKat!)。将UIEdgeInsetsZero硬编码以用于未来的iOS兼容性可能是有益的。

相反,我要求当前的插入值并根据需要调整底部值。

- (void)keyboardWillShow:(NSNotification *)sender {
    CGSize kbSize = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.height : kbSize.width;
    if (isIOS8()) height = kbSize.height;

    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = [[self tableView] contentInset];
        edgeInsets.bottom = height;
        [[self tableView] setContentInset:edgeInsets];
        edgeInsets = [[self tableView] scrollIndicatorInsets];
        edgeInsets.bottom = height;
        [[self tableView] setScrollIndicatorInsets:edgeInsets];
    }];
}

- (void)keyboardWillHide:(NSNotification *)sender {
    NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = [[self tableView] contentInset];
        edgeInsets.bottom = 0;
        [[self tableView] setContentInset:edgeInsets];
        edgeInsets = [[self tableView] scrollIndicatorInsets];
        edgeInsets.bottom = 0;
        [[self tableView] setScrollIndicatorInsets:edgeInsets];
    }];
}

答案 3 :(得分:8)

为了遇到这个问题的其他人,我在这里发布了必要的方法:

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *identifier = [NSString stringWithFormat: @"%d:%d", [indexPath indexAtPosition: 0], [indexPath indexAtPosition:1]];

    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc]  initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];

        UITextField *theTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 10, 130, 25)];

        theTextField.keyboardType = UIKeyboardTypeDefault;
        theTextField.returnKeyType = UIReturnKeyDone;
        theTextField.clearsOnBeginEditing = NO;
        theTextField.textAlignment = UITextAlignmentLeft;

        // (The tag by indexPath.row is the critical part to identifying the appropriate
        // row in textFieldDidBeginEditing and textFieldShouldEndEditing below:)

        theTextField.tag=indexPath.row;

        theTextField.delegate = self;

        theTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [theTextField setEnabled: YES];

        [cell addSubview:theTextField];

        [theTextField release];

    }

    return cell;
}

-(void) textFieldDidBeginEditing:(UITextField *)textField {

    int z = textField.tag;                                              

    if (z > 4) {

        // Only deal with the table row if the row index is 5 
        // or greater since the first five rows are already 
        // visible above the keyboard   

        // resize the UITableView to fit above the keyboard

        self.wordsTableView.frame = CGRectMake(0.0,44.0,320.0,200.0);       

        // adjust the contentInset

        wordsTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 10);        

        // Scroll to the current text field

        [wordsTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:z inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

    }
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {

    // Determine which row is being edited

    int z = textField.tag;  

    if (z > 4) {

        // resize the UITableView to the original size

        self.wordsTableView.frame = CGRectMake(0.0,44.0,320.0,416.0);       

        // Undo the contentInset
        wordsTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);         

    }

    return YES;

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    // Dismisses the keyboard when the "Done" button is clicked

    [textField resignFirstResponder];

    return YES;                                 

}

答案 4 :(得分:1)

尝试我的编码,这将有助于ypu <​​/ p>

tabelview.contentInset =  UIEdgeInsetsMake(0, 0, 210, 0);
[tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:your_indexnumber inSection:Your_section]
                 atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

答案 5 :(得分:1)

Apple有一篇官方帖子,解释了如何像在UITableViewController中那样自然地做到这一点。我的Stackoverflow答案已经解释了这个问题以及一个快速版本。

https://stackoverflow.com/a/31869898/1032179

答案 6 :(得分:1)

我需要一个简单的解决方案,对我来说helped

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        let pointInTable = textField.superview!.convert(textField.frame.origin, to: tableView)
        var tableVContentOffset = tableView.contentOffset
        tableVContentOffset.y = pointInTable.y
        if let accessoryView = textField.inputAccessoryView {
            tableVContentOffset.y -= accessoryView.frame.size.height
        }
        tableView.setContentOffset(tableVContentOffset, animated: true)
        return true;
    }

enter image description here

答案 7 :(得分:0)

您需要调整tableView本身的大小,使其不在键盘下。

-(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];

}

或者,您可以使用键盘通知;这样做效果稍好一些,因为你有更多的信息,并且在知道键盘出现的时候更加一致:

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

然后实施:

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

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

}

答案 8 :(得分:0)

我的代码。也许有人会有用: tableView

中的自定义textField单元格

的.m

    @property (nonatomic, strong) UITextField *currentCellTextField;

       CustomCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
            if (cell == nil) {
                NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
                cell = (CustomCell *)[nib objectAtIndex:0];
                cell.textfield.delegate = self;
            }
      - (void) textFieldDidBeginEditing:(UITextField *)textField
 {
  self.currentCellTextField = textField;

  CGPoint pnt = [self.organisationTableView convertPoint:textField.bounds.origin fromView:textField];
  NSIndexPath* path = [self.organisationTableView indexPathForRowAtPoint:pnt];

if (path.section >= 2) {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.organisationTableView.contentInset = UIEdgeInsetsMake(0, 0, kOFFSET_FOR_KEYBOARD, 0);
    CGPoint siize = self.organisationTableView.contentOffset;
    siize.y =(pnt.y-170);
    self.organisationTableView.contentOffset = CGPointMake(0, siize.y);
    [UIView commitAnimations];
    }
 }

  -(BOOL)textFieldShouldReturn:(UITextField *)textField
  {
   [textField resignFirstResponder];

CGPoint pnt = [self.organisationTableView convertPoint:textField.bounds.origin fromView:textField];
NSIndexPath* path = [self.organisationTableView indexPathForRowAtPoint:pnt];

 if (path.section >= 2) {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.organisationTableView.contentInset = UIEdgeInsetsZero;
    self.organisationTableView.contentOffset = CGPointMake(0, self.organisationTableView.contentOffset.y);
    [UIView commitAnimations];
      }

 return YES;
   }

答案 9 :(得分:0)

在我的情况下,我的UITableview位于另一个UIView中,并且UIvie位于主UIScrollview中。所以我对这些问题使用了更通用的解决方案。 我只是在特定的UIScrollView中找到了我的单元格的Y坐标,然后滚动到正确的点:

-(void)textFieldDidBeginEditing:(UITextField *)textField{
float kbHeight = 216;//Hard Coded and will not support lanscape mode
UITableViewCell *cell = (UITableViewCell *)[textField superview];
float scrollToHeight = [self FindCordinate:cell];
[(UIScrollView *)self.view setContentOffset:CGPointMake(0, scrollToHeight - kbHeight + cell.frame.size.height) animated:YES];
}

-(float)FindCordinate:(UIView *)cell{
float Ycordinate = 0.0;
while ([cell superview] != self.view) {
    Ycordinate += cell.frame.origin.y;
    cell = [cell superview];
}
Ycordinate += cell.frame.origin.y;
return Ycordinate;
}

答案 10 :(得分:0)

另一个简单的解决方案是为最后一个表格部分的页脚添加一个额外的空间:

- (float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == lastSection) {
        return keyboard height;
    }
    return 0;
}

我们也可以在此区域添加我们的图标。 :)

答案 11 :(得分:0)

您可以尝试将UITableViewController添加到UIViewController而不仅仅是表视图。这样你可以调用UITableViewController的viewWillAppear,一切都会起作用。

示例:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [tableViewController viewWillAppear:animated];
}

答案 12 :(得分:0)

我在@FunkyKat和@bmauter答案中添加了一些小功能(顺便提一句,它应该是接受的答案)

在键盘显示之前/之后保留常规表格视图边缘插入。

- (void)keyboardWillShow:(NSNotification *)sender
{
    CGSize kbSize = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.width : kbSize.height;

    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = self.tableView.contentInset;
        edgeInsets.bottom += height;
        self.tableView.contentInset = edgeInsets;
        edgeInsets = self.tableView.scrollIndicatorInsets;
        edgeInsets.bottom += height;
        self.tableView.scrollIndicatorInsets = edgeInsets;
    }];
}

- (void)keyboardWillHide:(NSNotification *)sender
{
    CGSize kbSize = [[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSTimeInterval duration = [[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    CGFloat height = UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? kbSize.width : kbSize.height;

    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = self.tableView.contentInset;
        edgeInsets.bottom -= height;
        self.tableView.contentInset = edgeInsets;
        edgeInsets = self.tableView.scrollIndicatorInsets;
        edgeInsets.bottom -= height;
        self.tableView.scrollIndicatorInsets = edgeInsets;
    }];
}