Scroll UITableView row to top, even when table contains only a few rows
I have a UITableView which sometimes has only a few rows. I would like a specific row, e.g. the 2nd out of 3, to appear at the top of the table. However, when the number of rows do not fill the entire table, calling the following has no effect:
[TableView scrollToRowAtIndexPath:[NSIndexPath index开发者_开发百科PathForRow:indexOfTopItem inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]
Is there a way I can force a row to appear at the top even with a limited number of rows in the table? Thanks
The only way to achieve this is to set the table's contentOffset. This will ensure the desired row appears at the top of the table, even when the rows do not fill up the entire table.
I'm not sure I understand exactly what you want but if you want to place a particular cell at the top of the table why not rearrange the data instead of the views?
Assuming your cell (row) data is not hard coded you can maybe do something like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([indexPath row] == 0){
// Load the data you want to appear at the top
}else {
// Load the rest of the data
}
}
You have to manually keep track of the top row data however so this might not be the best solution.
Alternatively if your data is in an array, you can swap the element you want on top with the first element in the array then call [myTableView reloadData] to reload the data. In this case you don't have to change cellForRowAtIndexPath.
Of course this is not very efficient since you're manipulating arrays and reloading your table but if your table only has a few rows and you don't have to do this swapping often it might be acceptable.
Rearrange the order, or have a button that shows the previous dates. You can use the numberOfRowsInSection
method to check a BOOL, and then set the right number of rows. Then in the cellForRowAtIndexPath
method, you again check the BOOL, and return the valid cells. On the button press, set the BOOL, and call the tableView's reloadData
method.
精彩评论