最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Swift中如何在TableView的最后添加一行cell并且滚动到底部

Swift crifan 4019浏览 0评论

代码:

            messageList.append(newMessage)
            
            messageTableView.reloadData()
           
           
let topIndexPath = NSIndexPath(forRow: (messageList.count 1), inSection: 0)
            messageTableView.scrollToRowAtIndexPath(topIndexPath, atScrollPosition: .Middle, animated: true)

已经可以实现:

更新了UITableViewDataSource的数据源messageList后,使得刷新列表,定位到最后的一行

但是:

效率太低

要去找效率高的。

swift tableview add cell scroll

swift tableview add new cell

swift tableview append new cell

ios – How to insert new cell into UITableView in Swift – Stack Overflow

Add Rows to Table View Tutorial in iOS8 with Swift – iOScreator

ios – How to insert new cell into UITableView in Swift – Stack Overflow

用代码:

            messageList.append(newMessage)
           
//            messageTableView.reloadData()
//            let topIndexPath = NSIndexPath(forRow: (messageList.count – 1), inSection: 0)
//            messageTableView.scrollToRowAtIndexPath(topIndexPath, atScrollPosition: .Middle, animated: true)
            messageTableView.beginUpdates()
           
messageTableView.insertRowsAtIndexPaths(
                [
NSIndexPath(forRow: messageList.count 1, inSection: 0)],
                withRowAnimation:
UITableViewRowAnimation.Automatic)
            messageTableView.endUpdates()

效果:

可以从上到下,感觉是fade方式滑动出现的:

但是没有自动滚动到,定位到新的行,要手动拖动才行:

swift tableview scroll to bottom

swift – scrollToRowAtIndexPath with UITableView does not work – Stack Overflow

然后代码:

            messageTableView.scrollToRowAtIndexPath(bottomIndexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)

即可滚动到底部:

[总结]

给TableView的数据源数组添加一个元素后:

新增一个Cell,并且滚动定位到底部的代码为:

//1. first beginUpdates
messageList.beginUpdates()
//2. insert/add new row tableview data
messageList.append(newMessage)
//3.then insert related row of tableview cell
let bottomIndexPath:NSIndexPath = NSIndexPath(forRow: messageList.count 1, inSection: 0)
messageTableView.insertRowsAtIndexPaths(
    [bottomIndexPath],
    withRowAnimation: UITableViewRowAnimation.Automatic)
//4. finally endUpdates
messageTableView.endUpdates()
//after update, can do scroll now
messageTableView.scrollToRowAtIndexPath(bottomIndexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)

即可。

转载请注明:在路上 » [已解决]Swift中如何在TableView的最后添加一行cell并且滚动到底部

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.161 seconds, using 22.28MB memory