【问题标题】:How to add last row to UITableView with smooth scrolling?如何通过平滑滚动将最后一行添加到 UITableView?
【发布时间】:2016-07-11 10:09:09
【问题描述】:

我正在使用 UITableView 构建聊天界面。我正在使用下面的代码添加单元格

self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: self.messageCards.count - 1, section: 0)], with: .bottom)
    self.tableView.endUpdates()

添加后我使用 scrollToRowAtIndexPath 来显示最后插入的行。

let indexPath = IndexPath(row: self.messageCards.count - 1, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)

但最后两个动画都在混合,滚动并不顺利。

【问题讨论】:

  • 想要的动画序列应该是什么......
  • @RohitKP 首先我想向上滚动并想使用动画显示新消息

标签: ios swift uitableview uiscrollview


【解决方案1】:

你可以试试这个,我已经测试过代码:

    arrayData.addObject(str)
    let indexpath = NSIndexPath(forRow: arrayData.count-1, inSection: 0)

    tblView.insertRowsAtIndexPaths([indexpath], withRowAnimation: UITableViewRowAnimation.Automatic)
    tblView.scrollToRowAtIndexPath(indexpath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)

以下是输出:如果您想要完整的源代码,请告诉我。

【讨论】:

  • 这在添加单元格大小固定的情况下可以正常工作,当中间添加一个大单元格时,动画会混乱,整个tableview闪烁,滚动不流畅。
【解决方案2】:

请看看这个。

 [UITableView animateWithDuration:5.0 delay:0.1 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messageCards.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    } completion:^(BOOL finished) {
        NSLog(@"animated");
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathWithIndex:self.messageCards.count-1] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }];

【讨论】:

    【解决方案3】:

    很神奇,但要实现滚动时的平滑添加只需要调用reloadData()

    func fetchNext(_ countToFetch: Int? = 10) {
    
        let existingCount = items?.count ?? 0
    
        networkService?.items(bySkip: existingCount, take: countToFetch, completion: { (data, error) in
    
            if let newItems = data?.items() as? [Element], newItems.count > 0 {
                self.items?.append(contentsOf: newItems)
                self.refreshCallback?()
            }
        })
    }
    

    回调是:

    datasource?.refreshCallback = { [weak self] in
    
        if #available(iOS 10.0, *) {
            self?.table.refreshControl?.endRefreshing()
        }
        self?.table.reloadData()
    }
    

    【讨论】:

    • reloadData 在我看来会更糟,因为所有行都将被重新加载,这不是必需的。
    【解决方案4】:
    [self.messageCards addObject:@"DATA Whatever you want"];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageCards.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多