ContentInsets不适用于UITableView

时间:2014-09-13 14:55:30

标签: ios uitableview uiresponder

我在TableView中有一个文本框,当用户选择一个开关时,它会出现(变得可见)并弹出一个键盘,当用户关闭开关时,TextBox消失,键盘隐藏。在键盘出现和消失的时候,我想稍微向上移动tableView,然后再回到原始位置。这是代码

-(IBAction)actionSwitch:(id)sender
{
isSearchTerm = [switchSearchTerm isOn];
[self.tableView reloadData];
if(isSearchTerm == YES)
{
    [txtSearchTerm becomeFirstResponder];
    floatBottom = self.tableView.contentInset.bottom;

    self.tableView.contentInset=UIEdgeInsetsMake(0,0,200,0);
    [self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForSelectedRow] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
else
{
    [txtSearchTerm resignFirstResponder];
    self.tableView.contentInset=UIEdgeInsetsMake(0,0,floatBottom,0);
    [self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForSelectedRow] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
}

其他部分没有将桌面视图恢复到原来的位置,请帮忙。

2 个答案:

答案 0 :(得分:2)

如果你的tableView位于导航控制器或导航控制器的rootViewController中,而你在iOS7 +上执行所有操作,并将UIViewController的属性automaticallyAdjustsScrollViewInsets设置为YES。您最好按照文档建议的那样处理键盘

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];

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

}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        [self.scrollView scrollRectToVisible:activeField.frame animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

还有另一种方法可以做到这一点。两者都可以在“移动键盘下的内容”“iOS文本编程指南”中找到

答案 1 :(得分:1)

我通过选择ViewController在属性检查器中的视图控制器属性下将顶部栏属性下的extend设置为NO来解决此问题。