首先,我會勸你考慮到沒有顯示在同一屏幕上的用戶這麼多的重複信息的設計 - 它會讓你的應用更直觀。例如,有一個切換所有非收藏行的選項。這樣,您可以顯示所有行並選擇收藏夾,或者如果您只想從收藏夾中選擇,可以隱藏它們。其次,如果您決定保留此設計,我建議您在插入新行時向下滾動表格視圖,而不是試圖阻止插入造成的滾動。對用戶來說,這看起來就像沒有發生過滾動一樣。方法如下:
UITableView有一個ContentOffset屬性,它是一個CGPoint。此點的y屬性是一個CGFloat,指示表視圖向下滾動多遠。所以,在你的代碼,當你添加行,同時也向下滾動屏幕:
// I use some variables for illustrative purposes here (you will need to provide them from your existing code):
// *** put your code to add or remove the row from favorites to your table view data source here ***
// start animation queue
[UIView beginAnimations:nil context:nil];
// check if a row is being added or deleted
if (isAddingRow) {
// if added, call to insert the row into the table view
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndexPath] withRowAnimation:UITableViewRowAnimationFade];
// also tell the table view to scroll down the height of a row
[tableView setContentOffset:CGPointMake(tableView.contentOffset.x, tableView.contentOffset.y + kHeightOfRow) animated:YES];
} else {
// if deleted, call to delete the row into the table view
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:deletedIndexPath] withRowAnimation:UITableViewRowAnimationFade];
// also tell the table view to scroll down the height of a row
[tableView setContentOffset:CGPointMake(tableView.contentOffset.x, tableView.contentOffset.y - kHeightOfRow) animated:YES];
}
// launch animations
[UIView commitAnimations];
另外,如果你在選擇了行不使用動畫,你其實可以關閉動畫(做上面一樣沒有任何的動畫):
// check if a row is being added or deleted
if (isAddingRow) {
// if added, call to insert the row into the table view
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndexPath] withRowAnimation:UITableViewRowAnimationNone];
// also tell the table view to scroll down the height of a row
[tableView setContentOffset:CGPointMake(tableView.contentOffset.x, tableView.contentOffset.y + kHeightOfRow) animated:NO];
} else {
// if deleted, call to delete the row into the table view
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:deletedIndexPath] withRowAnimation:UITableViewRowAnimationNone];
// also tell the table view to scroll down the height of a row
[tableView setContentOffset:CGPointMake(tableView.contentOffset.x, tableView.contentOffset.y - kHeightOfRow) animated:NO];
}
您也想進行setContentOffset:動畫:方法只有當表視圖contentSize是(或即將)比的tableView大小。希望有所幫助!