我的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))
}
}
我希望dispatch_sync部分可以将
animateBackgroundColor
方法的执行延迟到滚动完成之前。不幸的是,事实并非如此,当该行尚不可见时,就会调用animateBackgroundColor
-> cellForRowAtIndexPath
returns nil
并且我的动画不会发生。如果不需要滚动,则动画可以正常工作。谁能告诉我如何在滚动完成之前将
animateBackgroundColor
函数的执行延迟?非常感谢您的问候
最佳答案
延迟动画似乎不是解决此问题的好方法,因为scrollToRowAtIndexPath
动画持续时间是根据当前列表项到指定项之间的距离设置的。要解决此问题,您需要在实现scrollToRowAtIndexPath
动画后通过执行scrollViewDidEndScrollingAnimation
UITableViewDelegate方法来执行animateBackgroudColor。这里最棘手的部分是获取tableview滚动的indexPath。可能的解决方法:
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
}
关于ios - 等到 swift 完成scrollToRowAtIndexPath,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30641801/