在寻找解决方案时,我发现您的 placesTableView 的 contentInset 底部在不同状态下一直在改变。当您可以看到地图并且 tableView 表现正常时,初始状态下它为 0。当您点击搜索字段后键盘弹出时,它被设置为 216。我想这是 tableView 和键盘之间某些自动通信(通过通知或者在 PlacesQueryTableViewController 中执行的一些操作)引起的。这很好,因为我们希望底部的插入会在键盘弹出时设置为键盘顶部。现在问题来了,当我点击取消按钮时,contentInset.bottom 被设置为 -216。
我无法完全解释为什么会发生这种情况,但我怀疑这与插入的自动更改方式有关。我猜测它做了类似于
tableView.contentInset.bottom -= heightOfKeyboard
的事情,而这可能是在动画完成后才发生的,而不是之前。您的问题的源头在于您在动画完成之前更改了 contentInset 底部,因此也在那个自动更改发生之前进行更改。因此,您将底部设置为 0,用户一旦点击取消,系统就会进来并将其减小键盘的高度,结果为 216。这至少是我认为发生的事情。
要解决这个问题,避免更改 contentInset 底部,并只更改顶部。虽然
placesTableView.contentInset.top
是只读的,但如果您像下面的代码一样操作,您可以绕过它。我只更改了每个方法中与插入相关的两行代码,希望您能理解我的做法。
-(void)enableInset {
NSLog(@"Enabling insets");
CGFloat offSet = [placestableViewController tableView:placestableViewController.tableView heightForRowAtIndexPath:nil] - 30.0f;
UIEdgeInsets inset = placesTableView.contentInset;
inset.top = placesMapView.frame.size.height - offSet;
placesTableView.contentInset = inset;
placesTableView.contentOffset = CGPointMake(0.0f, -(placesMapView.frame.size.height - offSet));
placesTableView.scrollIndicatorInsets = inset;
placesMapView.hidden = NO;
[placestableViewController loadObjects];}
- (void)disableInset {
NSLog(@"Disable insets");
CGFloat offset = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
UIEdgeInsets inset = placesTableView.contentInset;
inset.top = offset;
placesTableView.contentInset = inset;
placesTableView.contentOffset = CGPointMake(0.0f, -offset);
placesTableView.scrollIndicatorInsets = inset;
placesMapView.hidden = YES;}
顺便说一下,如果您想知道我如何在不同状态下找到contentInset值,那很简单。我所做的是在- (void)viewDidLoad
中将自己设置为placesTableView的代理,像这样placesTableView.delegate = self;
。我还必须更改@interface
语句以@interface KrackMapViewController() <UITableViewDelegate>
的方式来表示我们符合UITableViewDelegate。现在,这里有个技巧:UITableViewDelegate符合UIScrollViewDelegate。这意味着我们可以实现滚动视图委托方法。特别有趣的一个方法是:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
NSLog(@"Did scroll with insetTop: %f, insetBottom: %f, contentOffset: %f", placesTableView.contentInset.top,
placesTableView.contentInset.bottom,
placesTableView.contentOffset.y);
}
这让我们知道您何时开始拖动tableView,在那里简单地NSLog出不同的参数。
希望这对您有所帮助。如果这对您有用,请告诉我。