【问题标题】:setContentOffset is not scrolling table to last cellsetContentOffset 不是将表格滚动到最后一个单元格
【发布时间】:2017-02-22 09:13:18
【问题描述】:

我正在尝试使用 contentOffset 方法将表格滚动到最后一行。当数据不多时,此方法可以正常工作,但如果用户滚动太多,它确实需要表格到最后一个单元格。我正在使用以下代码

   self.delegate.table.setContentOffset(CGPointMake(0, table.contentSize.height -  table.frame.size.height), animated: false)

【问题讨论】:

    标签: ios swift uitableview autolayout


    【解决方案1】:

    我认为首选的方式是调用

    func scrollToRow(at indexPath: IndexPath, 
              at scrollPosition: UITableViewScrollPosition, 
        animated: Bool)
    

    UITableView,见here

    【讨论】:

    • 当我使用这种方法时,如果单元格数量很大,则需要很长时间。
    • 如果将动画设置为 false 会怎样?
    • 两种情况下的结果都是一样的。
    【解决方案2】:

    为什么不使用scrollToRow 方法。

    let lastIndex:NSIndexPath = NSIndexPath(forRow: tableView.numberOfRowsInSection(0) - 1, inSection: 0)
    
    tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: .Middle, animated: true)
    

    滚动所需的时间取决于 contentSize。奇怪的是,当动画设置为 false 时,仍然使用这个时间。为了让它更活泼,在动画块中设置您自己的持续时间。

    UIView.animateWithDuration(aSmallValue) { 
                self.tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: .Middle, animated: true)
            }
    

    【讨论】:

    • 因为如果单元格数量很大,滚动会花费太多时间。
    • 请查看我关于缓慢的修改后的答案
    • xcode是从什么时候开始在swift文件中编译obj-C代码的?
    • 还是很慢。
    【解决方案3】:

    试试这个对我有用, Objective-C的代码

     NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([self.tableView numberOfRowsInSection:0] - 1) inSection:0];
     [[self tableView] scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    

    Swift 3.0 代码

     let scrollIndexPath:IndexPath = IndexPath(row: (tblView.numberOfRows(inSection: 0)-1), section: 0)
     tblView.scrollToRow(at: scrollIndexPath, at: .bottom, animated: false)
    

    【讨论】:

      【解决方案4】:
      let offsetOfTable = CGPoint(x:0, y:self.yourTableView.contentSize.height - self.yourTableView.frame.size.height + self.FOOTER_HEIGHT);
      self.yourTableView.contentOffset = offsetOfTable;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多