【发布时间】:2015-11-06 15:27:20
【问题描述】:
我的应用是用 Swift 2.0 编写的,需要在 iOS 8.1 或更高版本上运行。我使用 Xcode 7.0。
我正在使用标准的 UITableViewController。我的 UITableView 只有一种自定义原型单元格 CustomCell,它是 UITableViewCell 的子类。 CustomCell 里面有几个 UILabel,它们都有清晰的背景颜色和固定的宽度和高度。一切都在 Interface Builder 中布置。
我经常(10+ 次/秒)从另一个来源接收数据。我单元格中的标签必须根据收到的数据更新其内容。我还需要为标签背景颜色设置动画。为此,我使用以下内容:
extension UIView {
func fadeOut() {
self.layer.backgroundColor = UIColor.blackColor().CGColor
UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.layer.backgroundColor = UIColor.clearColor().CGColor
}, completion: nil)
}
}
我使用以下代码更新标签:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomCell
let oldText = customLabel.text
let newText = dataForLabels[indexPath.row].custom
if newText != oldText {
cell.customLabel.fadeOut()
}
cell.customLabel.text = dataForLabels[indexPath.row].custom
return cell
}
而我的更新(回调)方法如下所示:
var dataForLabels:[Int:(custom: String?, anotherCustom: String?)] = [:]
func updateData(CustomData data) {
for d in data {
dataForLabels[d.index] = (custom: data.custom, anotherCustom: data.anotherCustom)
}
tableView.reloadData()
}
现在,问题本身:
当特定单元格/标签的数据没有变化时,动画应该继续(淡入淡出效果,2s)。当数据发生变化时,动画应该重新开始。
当我调用reloadData()时,数据没有变化,动画被移除/停止,即标签的背景颜色突然清晰,没有褪色效果。
我尝试将 reloadData() 分派到主线程,但没有帮助。我试过用 CABasicAnimation 代替 animateWithDuration(),但也没有解决问题。
我尝试了类似的场景,但根本不使用表格(只是几个 UIView 而不是单元格)并且它可以工作。问题是当我使用 reloadData() 时。
我试过调试它,但是我在反汇编方面做得不好。我看到 layout_if_needed() 被调用并且某处所有的动画都被删除了。
我怀疑的是,当调用 reloadData() 时,布局管理器认为由于某种原因约束发生了变化,需要更新布局,这会破坏所有动画。
有没有解决这个问题的方法,最好是我可以继续使用 Interface Builder 的方法?
任何帮助将不胜感激。
【问题讨论】:
-
可能是这个问题的重复:stackoverflow.com/a/7528883/239816
标签: ios swift uitableview