OGeek|极客世界-中国程序员成长平台

标题: ios - iOS8 和 iOS9 中的 UITableView contentSize 计算方式不同? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 14:53
标题: ios - iOS8 和 iOS9 中的 UITableView contentSize 计算方式不同?

我正在使用下面的代码来强制 uitableview “对齐行”:

- (void)scrollViewDidEndDraggingUIScrollView *)scrollView willDecelerateBOOL)decelerate {
    // if decelerating, let scrollViewDidEndDecelerating: handle it
    if (decelerate == NO) {
        [self centerTable];
    }
}

- (void)scrollViewDidEndDeceleratingUIScrollView *)scrollView {
    [self centerTable];
}

- (void)centerTable {
    NSIndexPath *pathForCenterCell = [self.tableView indexPathForRowAtPoint:CGPointMake(CGRectGetMidX(self.tableView.bounds), CGRectGetMidY(self.tableView.bounds))];

    [self.tableView scrollToRowAtIndexPath:pathForCenterCell atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

它在 iOS9 中运行良好,但在 iOS8 中,表格 View 不允许我捕捉到第一行或最后一行。如果我在索引路径计算之后在 centerTable 中放置一个断点,我会为表格 View 得到这个:

iOS9:

<UITableView: 0x7fb9a6ed8600; frame = (0 0; 300 132); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7fb9ae14cae0>; layer = <CALayer: 0x7fb9ad1b1540>; contentOffset: {0, 0}; contentSize: {300, 220}>

iOS8:

<UITableView: 0x7ff6e2d59800; frame = (0 0; 300 132); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7ff6e8726130>; layer = <CALayer: 0x7ff6e214b450>; contentOffset: {0, 0}; contentSize: {300, 132.5}>

请注意,除了 contentSize 之外,一切都是一样的。这导致与 iOS9 相比,iOS8 中的索引路径为 n+1

那么,为什么在 iOS8 系统中 contentSize 的计算方式不同???解决方法是什么?



Best Answer-推荐答案


虽然我不明白为什么 contentSize 不同,但这里是我针对准确居中问题的解决方法:

- (void)centerTableViewAnimatedBOOL)animated {
     NSIndexPath *centerCellIndexPath = [self.tableView indexPathForRowAtPoint:CGPointMake(CGRectGetMidX(self.tableView.bounds), CGRectGetMidY(self.tableView.bounds))];

     CGPoint contentOffset = CGPointMake(0, (centerCellIndexPath.row * self.tableView.rowHeight) - ((self.tableView.frame.size.height / 2) - (self.tableView.rowHeight / 2)));

     [self.tableView setContentOffset:contentOffset animated:animated];
}

所以基本上,我没有尝试使用 scrollToRowAtIndexPath,而是直接设置 contentOffset(您可以对其进行动画处理,这很好)。这似乎在 iOS 8 和 iOS 9 上运行良好。

关于ios - iOS8 和 iOS9 中的 UITableView contentSize 计算方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589811/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4