【问题标题】:Calling topLayoutGuide breaks scrolling altogether?调用 topLayoutGuide 会完全中断滚动吗?
【发布时间】:2013-10-25 16:55:23
【问题描述】:

我在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
    

我遇到的问题是:

  1. 如果我取消注释标记为[1] 的行,则会应用正确的插图,但滚动表格视图不再起作用。当我尝试滚动时,松开手指后表格会弹回初始滚动位置。此行为也由对 [self topLayoutGuide] 的普通调用触发,而无需将结果分配给任何对象。

  2. 如果我取消注释行 [2] 而不是 [1],滚动工作。也应用了 100 pt 的插图。但是现在会自动调整初始滚动位置,使内容与状态栏重叠。

([*]: 这似乎只与包含导航控制器结合使用。我在这个例子中似乎没有什么不同,但我想禁用任何自动行为以确保。)

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

【问题讨论】:

  • 我刚刚发现对[self topLayoutGuide] 的调用导致表视图的contentSize 属性从正确的值更改为{0, 0}。不过不知道为什么会这样……
  • 可能是一个错误,也有那个。
  • 这里也一样。这令人难以置信的沮丧。感觉就像旧的 iOS 3.0 时代一样好。

标签: ios objective-c uiviewcontroller ios7


【解决方案1】:

这绝对是 iOS 7 中的一个错误(在 7.1 中似乎没有修复),但似乎只影响UITableViewControllers。我转而使用带有嵌入式UITableViewUIViewController,因为我没有使用静态单元格,也不需要UITableViewController 为您提供的任何“魔法”。

一旦我手动连接了UITableViewDataSourceUITableViewDelegate,我就可以开始使用self.topLayoutGuide 而不会弄乱 tableView 的 contentSize。

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

【讨论】:

    【解决方案2】:

    对我来说同样的事情,而不是获取 topLayoutGuide,试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 2015-09-01
      • 1970-01-01
      • 2016-03-25
      • 2015-04-22
      相关资源
      最近更新 更多