Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

iphone - How to Start UITableView on the Last Cell?

In Apple's Messages app, when you click a correspondent's name and switch to the table view of the conversation (with balloons for each message), the table appears scrolled all the way to the end. No animation or anything, it's just there.

Similarly, in Tweetie 2, when you load the tweets view, it appears right where you last looked at it. No animation to get there, it's just there, as if none of the cells above were loaded.

How do these apps do this? Are they calling scrollToRowAtIndexPath:atScrollPosition:animated: somewhere in the table controller? If so, how do they know what to pass to atScrollPosition:? And in what method is it called?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

scrollToRowAtIndexPath should work.

In viewWillAppear:, try this:

[theTableView reloadData];    
NSIndexPath* ip = [NSIndexPath indexPathForRow:rowNumberHere inSection:sectionNumberHere];
[theTableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:NO];

rowNumberHere is the row number in the data source you want to scroll to.

atScrollPosition is just one of the values in the UITableViewScrollPosition enum which can determine where on the screen the row number you want will show up. However, depending on the number of rows and which row you are scrolling to, it may not make a difference.

Putting reloadData: avoids an exception if the data is not loaded yet in viewWillAppear:. If you put the scrollToRowAtIndexPath in viewDidAppear:, you would not need the reloadData: but you will see the table jump a little which you say you don't want.

Edit: @Theory, try changing your code as follows...

[tableView reloadData];
int lastRowNumber = [tableView numberOfRowsInSection:0] - 1;
NSIndexPath* ip = [NSIndexPath indexPathForRow:lastRowNumber inSection:0];
[tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:NO];

Please note numberOfRowsInSection returns row count, not the last row number (which is row count - 1).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...