fuz*_*oat 60 iphone cocoa-touch objective-c
我有一个UITableView与cells被动态地更新.一切正常,除了tableview.reload调用时(见下文)刷新cells表中我希望表滚动到底部以显示新条目.
- (void)reloadTable:(NSNotification *)notification {
NSLog(@"RELOAD TABLE ...");
[customTableView reloadData];
// Scroll to bottom of UITable here ....
}
Run Code Online (Sandbox Code Playgroud)
我打算使用scrollToRowAtIndexPath:atScrollPosition:animated:但后来注意到我无法访问indexPath.
有谁知道怎么做,或者delegate我可以使用的回调?
Max*_*Max 121
使用:
NSIndexPath* ipath = [NSIndexPath indexPathForRow: cells_count-1 inSection: sections_count-1];
[tableView scrollToRowAtIndexPath: ipath atScrollPosition: UITableViewScrollPositionTop animated: YES];
Run Code Online (Sandbox Code Playgroud)
或者您可以手动指定部分索引(如果一个部分=> index = 0).
Mic*_*son 38
另一个解决方案是垂直翻转表格,并垂直翻转每个单元格:
初始化时将转换应用于UITableView:
tableview.transform = CGAffineTransformMakeScale(1, -1);
Run Code Online (Sandbox Code Playgroud)
并在cellForRowAtIndexPath中:
cell.transform = CGAffineTransformMakeScale(1, -1);
Run Code Online (Sandbox Code Playgroud)
这样您就不需要解决滚动问题的方法,但是您需要更加关注contentInsets/contentOffsets和页眉/页脚交互.
mkr*_*ral 33
-(void)scrollToBottom{
[self.tableView scrollRectToVisible:CGRectMake(0, self.tableView.contentSize.height - self.tableView.bounds.size.height, self.tableView.bounds.size.width, self.tableView.bounds.size.height) animated:YES];
}
Run Code Online (Sandbox Code Playgroud)
//In swift
var iPath = NSIndexPath(forRow: self.tableView.numberOfRowsInSection(0)-1,
inSection: self.tableView.numberOfSections()-1)
self.tableView.scrollToRowAtIndexPath(iPath,
atScrollPosition: UITableViewScrollPosition.Bottom,
animated: true)
Run Code Online (Sandbox Code Playgroud)
斯威夫特 3
对于这里所有试图弄清楚如何解决这个问题的人来说,关键是在以下.layoutIfNeeded()之后调用方法.reloadData():
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.setContentOffset(CGPoint(x: 0, y: tableView.contentSize.height - tableView.frame.height), animated: false)
Run Code Online (Sandbox Code Playgroud)
我正在处理多个部分,UITableView并且效果很好。
小智 6
斯威夫特 5
extension UITableView {
func scrollToBottom(animated: Bool = true) {
let section = self.numberOfSections
if section > 0 {
let row = self.numberOfRows(inSection: section - 1)
if row > 0 {
self.scrollToRow(at: IndexPath(row: row-1, section: section-1), at: .bottom, animated: animated)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是另一个解决方案,当像元高度很大时,在我的情况下效果很好。
- (void)scrollToBottom
{
CGPoint bottomOffset = CGPointMake(0, _bubbleTable.contentSize.height - _bubbleTable.bounds.size.height);
if ( bottomOffset.y > 0 ) {
[_bubbleTable setContentOffset:bottomOffset animated:YES];
}
}
Run Code Online (Sandbox Code Playgroud)
因为这是您可能真的想经常使用的东西,所以建议您在UITableView上创建一个类扩展:
extension UITableView {
func scrollToBottom(animated: Bool = true) {
let section = self.numberOfSections
if section > 0 {
let row = self.numberOfRowsInSection(section - 1)
if row > 0 {
self.scrollToRowAtIndexPath(NSIndexPath(forRow: row - 1, inSection: section - 1), atScrollPosition: .Bottom, animated: animated)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)