调用topLayoutGuide完全打破滚动?

时间:2013-10-25 16:55:23

标签: ios objective-c uiviewcontroller ios7

我遇到了topLayoutGuide方法的奇怪问题,我必须在setAutomaticallyAdjustsScrollViewInsets:不起作用的情况下使用它。为了缩小问题的原因,我创建了以下最小的示例,它只是为测试设置了一个基本的表视图:

  1. 在Xcode中设置新的iOS Single View应用程序。
  2. 在ViewController.m的实现中粘贴以下代码:

    @implementation ViewController
    
    - (void)loadView
    {
        [self setTableView:[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain]];
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self setAutomaticallyAdjustsScrollViewInsets:NO]; // [*]
    }
    
    - (void)viewDidLayoutSubviews
    {
        UITableView *tableView = [self tableView];
    
        UIEdgeInsets insets = [tableView contentInset];
        // insets.top = [[self topLayoutGuide] length]; // [1]
        // insets.top = 100;                            // [2]
    
        [tableView setContentInset:insets];
        [tableView setScrollIndicatorInsets:insets];
    }
    
    #pragma mark - Table view data source
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 100;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
    
        [[cell textLabel] setText:[NSString stringWithFormat:@"%d", [indexPath row]]];
    
        return cell;
    }
    
    @end
    
  3. 我遇到的问题是:

    1. 如果我取消注释标有[1]的行,则会应用正确的插入内容,但滚动表格视图不再有效。当我尝试滚动时,表格会在我松开手指后弹回到初始滚动位置。通过对[self topLayoutGuide]的简单调用也会触发此行为,而不会将结果分配给任何内容。

    2. 如果我取消注释[2] 而不是<{1}} ,则滚动有效。也应用了100 pt的插图。但现在自动调整初始滚动位置,以便内容以状态栏为基础。

    3. [1]:这似乎只是与包含导航控制器的组合做了什么。我似乎没有在这个例子中有所作为,但我想禁用任何自动行为只是为了确定。)

      有什么明显的我做错了吗?我真的很茫然。

2 个答案:

答案 0 :(得分:11)

这绝对是iOS 7中的一个错误(在7.1中似乎没有修复),但似乎只影响UITableViewControllers。我切换到使用嵌入式UIViewController的{​​{1}},因为我没有使用静态单元格,也不需要UITableView给你的任何“魔法”。

我手动连接UITableViewControllerUITableViewDataSource后,我就可以开始使用UITableViewDelegate而不会弄乱tableView的contentSize。

在Apple修复错误之前,这对我来说是一个可接受的解决方法。

答案 1 :(得分:2)

对我来说,不是获取topLayoutGuide,而是尝试这个:

CGFloat topOffset = CGRectGetMaxY(self.refController.navigationController.navigationBar.frame);