stu*_*000 6 uitableview ios swift
我的UITableView单元格比屏幕上的多。当我从我的数据模型收到通知时,我想跳到特定的行并显示一个非常基本的动画。
我的代码是:
func animateBackgroundColor(indexPath: NSIndexPath) {
dispatch_async(dispatch_get_main_queue()) {
NSLog("table should be at the right position")
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? BasicCardCell {
var actColor = cell.backgroundColor
self.manager.vibrate()
UIView.animateWithDuration(0.2, animations: { cell.backgroundColor = UIColor.redColor() }, completion: {
_ in
UIView.animateWithDuration(0.2, animations: { cell.backgroundColor = actColor }, completion: { _ in
self.readNotificationCount--
if self.readNotificationCount >= 0 {
var legicCard = self.legicCards[indexPath.section]
legicCard.wasRead = false
self.reloadTableViewData()
} else {
self.animateBackgroundColor(indexPath)
}
})
})
}
}
}
func cardWasRead(notification: NSNotification) {
readNotificationCount++
NSLog("\(readNotificationCount)")
if let userInfo = notification.userInfo as? [String : AnyObject], let index = userInfo["Index"] as? Int {
dispatch_sync(dispatch_get_main_queue()){
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: index), atScrollPosition: .None, animated: true)
self.tableView.layoutIfNeeded()
NSLog("table should scroll to selected row")
}
self.animateBackgroundColor(NSIndexPath(forRow: 0, inSection: index))
}
}
Run Code Online (Sandbox Code Playgroud)
我希望 dispatch_sync 部分会延迟我的animateBackgroundColor方法的执行,直到滚动完成。不幸的是,情况并非如此,因此animateBackgroundColor当该行尚不可见时会被调用 ->cellForRowAtIndexPath returns nil并且我的动画不会发生。如果不需要滚动,动画就可以正常工作。
谁能告诉我如何延迟我的animateBackgroundColor函数的执行直到滚动完成?
非常感谢和亲切的问候
延迟动画似乎不是一个好的解决方案,因为scrollToRowAtIndexPath动画持续时间是根据当前列表项到指定项的距离设置的。要解决此问题,您需要在scrollToRowAtIndexPath动画完成后通过实现scrollViewDidEndScrollingAnimationUITableViewDelegate 方法执行 animateBackgroudColor。这里棘手的部分是获取 tableview 滚动的索引路径。一个可能的解决方法:
var indexPath:NSIndexpath?
func cardWasRead(notification: NSNotification) {
readNotificationCount++
NSLog("\(readNotificationCount)")
if let userInfo = notification.userInfo as? [String : AnyObject], let index = userInfo["Index"] as? Int{
dispatch_sync(dispatch_get_main_queue()){
self.indexPath = NSIndexPath(forRow: 0, inSection: index)
self.tableView.scrollToRowAtIndexPath(self.indexPath, atScrollPosition: .None, animated: true)
self.tableView.layoutIfNeeded()
NSLog("table should scroll to selected row")
}
}
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
self.animateBackgroundColor(self.indexPath)
indexPath = nil
}
Run Code Online (Sandbox Code Playgroud)