【问题标题】:Scroll UITableView Cell beyond table bounds将 UITableView 单元格滚动到表格边界之外
【发布时间】:2015-02-09 13:14:23
【问题描述】:

我有一个高度变化的 UITableView。

我希望在每个单元格选择中通过将其移动到屏幕中间来获得“焦点”。问题是移动表格中的上下单元格,因为它们不能滚动超出表格的上限和下限。我也更喜欢用动画来做到这一点..

有什么建议吗? 谢谢!

【问题讨论】:

    标签: ios objective-c uitableview cell


    【解决方案1】:

    我创建了一个小例子来说明如何实现这一点: https://github.com/vkozlovskyi/CenterCellExample

    您只需要计算 UITableView 的滚动偏移量,并为更改设置动画:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
        // Get offset for cell
        CGFloat centerOffset = self.tableView.frame.size.height / 2 - self.tableView.rowHeight / 2;
    
        // Content offset
        CGFloat total = indexPath.row * self.tableView.rowHeight;
    
        [UIView animateWithDuration:0.3 animations:^{
            self.tableView.contentOffset = CGPointMake(0, total - centerOffset);
        }];
    }
    

    它适用于所有单元格,也适用于上层和下层。

    【讨论】:

    • 但这仅适用于中间单元格,上下滚动不会弯曲边界..
    • 我改了答案,试试这个解决方案
    【解决方案2】:

    您可以使用 contentInset 属性为表格视图的内容添加额外的空间。在表格视图的上方和下方添加额外的空间将使您的单元格一直滚动到表格视图的中间。

    UITableView * tableView = self.tableView ;
    CGRect bounds = self.tableView.bounds ;
    CGFloat extraSpaceNeeded = 0.5 * ( bounds.size.height - tableView.rowHeight ) ;
    tableView.contentInset = (UIEdgeInsets){ .top = -extraSpaceNeeded, .bottom = -extraSpaceNeeded } ;
    

    现在你可以使用

    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle 动画:动画];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      • 2019-07-25
      相关资源
      最近更新 更多