Продолжительность анимации строки UITableView и обратный вызов завершения
Есть ли способ указать продолжительность анимации строк UITableView или получить обратный вызов после завершения анимации?
То, что я хотел бы сделать, - это прокрутить индикаторы прокрутки после завершения анимации. Выполнение вспышки перед этим ничего не делает. До сих пор обходной путь, который у меня есть, заключается в задержке на полсекунды (это, по-видимому, продолжительность анимации по умолчанию), то есть:
[self.tableView insertRowsAtIndexPaths:newRows
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView performSelector:@selector(flashScrollIndicators)
withObject:nil
afterDelay:0.5];
Ответы
Ответ 1
В настоящее время, если вы хотите сделать это, есть новая функция , начиная с iOS 11:
- (void)performBatchUpdates:(void (^)(void))updates
completion:(void (^)(BOOL finished))completion;
В обновлениях вы размещаете тот же код, что и в разделе beginUpdates()/endUpdates. И завершение выполняется после всех анимаций.
Ответ 2
Просто наткнулся на это. Вот как это сделать:
Objective-C
[CATransaction begin];
[tableView beginUpdates];
[CATransaction setCompletionBlock: ^{
// Code to be executed upon completion
}];
[tableView insertRowsAtIndexPaths: indexPaths
withRowAnimation: UITableViewRowAnimationAutomatic];
[tableView endUpdates];
[CATransaction commit];
Swift
CATransaction.begin()
tableView.beginUpdates()
CATransaction.setCompletionBlock {
// Code to be executed upon completion
}
tableView.insertRowsAtIndexPaths(indexArray, withRowAnimation: .Top)
tableView.endUpdates()
CATransaction.commit()
Ответ 3
Развернувшись на отличном ответе karwag, обратите внимание, что на iOS 7, окружающая CATransaction с анимацией UIView, вы можете контролировать продолжительность анимации таблицы.
[UIView beginAnimations:@"myAnimationId" context:nil];
[UIView setAnimationDuration:10.0]; // Set duration here
[CATransaction begin];
[CATransaction setCompletionBlock:^{
NSLog(@"Complete!");
}];
[myTable beginUpdates];
// my table changes
[myTable endUpdates];
[CATransaction commit];
[UIView commitAnimations];
Продолжительность анимации UIView не влияет на iOS 6. Возможно, анимация таблицы iOS 7 реализована по-разному на уровне UIView.
Ответ 4
Укорачивание Хороший ответ Brent, по крайней мере для iOS 7 вы можете обернуть все это в [UIView animateWithDuration: delay: options: animations: completion:] call:
[UIView animateWithDuration:10 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[self.tableView beginUpdates];
[self.tableView endUpdates];
} completion:^(BOOL finished) {
// completion code
}];
хотя я не могу переопределить кривую анимации по умолчанию из ничего, кроме EaseInOut.
Ответ 5
Этот ад полезный трюк!
Я написал расширение UITableView, чтобы не писать записи CATransaction все время.
import UIKit
extension UITableView {
/// Perform a series of method calls that insert, delete, or select rows and sections of the table view.
/// This is equivalent to a beginUpdates() / endUpdates() sequence,
/// with a completion closure when the animation is finished.
/// Parameter update: the update operation to perform on the tableView.
/// Parameter completion: the completion closure to be executed when the animation is completed.
func performUpdate(_ update: ()->Void, completion: (()->Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
// Table View update on row / section
beginUpdates()
update()
endUpdates()
CATransaction.commit()
}
}
Это используется так:
// Insert in the tableView the section we just added in sections
self.tableView.performUpdate({
self.tableView.insertSections([newSectionIndex], with: UITableViewRowAnimation.top)
}, completion: {
// Scroll to next section
let nextSectionIndexPath = IndexPath(row: 0, section: newSectionIndex)
self.tableView.scrollToRow(at: nextSectionIndexPath, at: .top, animated: true)
})
Ответ 6
Здесь приведена версия karwag
CATransaction.begin()
tableView.beginUpdates()
CATransaction.setCompletionBlock { () -> Void in
// your code here
}
tableView.insertRowsAtIndexPaths(indexArray, withRowAnimation: .Top)
tableView.endUpdates()
CATransaction.commit()
Ответ 7
Для меня мне это понадобилось для коллекцииView. Я сделал простое расширение, чтобы решить эту проблему:
extension UICollectionView {
func reloadSections(sections: NSIndexSet, completion: () -> Void){
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
self.reloadSections(sections)
CATransaction.commit()
}
}
Ответ 8
Переопределить tableView -insertRowsAtIndexPaths: и реализовать пользовательскую вставку/(или удаление с помощью собственного метода), которую вы хотите. Я не пытался это сам, хотя.
Ответ 9
Вы можете попытаться обернуть insertRowsAtIndexPath в
- (void)beginUpdates
- (void)endUpdates
затем выполните флэш-память.