Swift 闪烁表视图单元格
在向表视图添加一组新数据后,我希望显示新数据的单元格呈绿色闪烁5秒钟。我使用了UIView的扩展。我在“cellForRowAtIndexPath”中调用扩展名,但它会永久性地将单元格变为绿色,并且不再返回默认背景色。以下是我正在使用的扩展:Swift 闪烁表视图单元格,swift,uitableview,uiviewanimation,Swift,Uitableview,Uiviewanimation,在向表视图添加一组新数据后,我希望显示新数据的单元格呈绿色闪烁5秒钟。我使用了UIView的扩展。我在“cellForRowAtIndexPath”中调用扩展名,但它会永久性地将单元格变为绿色,并且不再返回默认背景色。以下是我正在使用的扩展: extension UIView { func blink(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, alpha: CGFloat = 0.0) { UIVie
extension UIView {
func blink(duration: TimeInterval = 0.5, delay: TimeInterval = 0.0, alpha: CGFloat = 0.0) {
UIView.animate(withDuration: duration, delay: delay, options: [.curveEaseInOut, .repeat, .autoreverse], animations: {
self.backgroundColor = .systemGreen
})
}
}
self.blink()在“cellForRowAtIndexPath”中调用
我不知道为什么动画不起作用,有人有解决办法吗?这是我现在设法找到的解决问题的有效答案 首先是闪烁的扩展: 使用
.repeat.autoreverse
我无法在动画返回默认颜色时停止动画,因为默认颜色看起来不太好看。所以我决定自己写动画,让细胞以这种方式闪烁3次:
extension UIView {
func blink(duration: TimeInterval = 1.4, repetitions: Int = 3) {
var remainingReps = repetitions
UIView.animate(withDuration: duration, animations: {
self.backgroundColor = Colors.primaryAlpha
}) { (error) in
UIView.animate(withDuration: duration, animations: {
self.backgroundColor = .systemBackground
}) { (error) in
remainingReps -= 1
if remainingReps > 0 {
self.blink(duration: duration, repetitions: remainingReps)
}
}
}
}
}
您可以通过其“repetitions”(重复次数)参数选择希望单元格闪烁的次数。
现在在tableview中为tableview将显示单元格添加以下代码:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let dataSet = myData[indexPath.row]
let myCell = cell as! YourCellType
myCell.checkIfShouldBlink(data: dataSet)
}
}
最后,在TableViewCell类中:
func checkIfShouldBlink(data: MyDataObject){
//Here you can implement any kind of logic to have the cell blink depending
//on your dataSet. In my case for exmaple, if the timestamp of the data is
//less than 5 secs old (new Data) i have the cell blink.
if data.whatEverLogicYouWantToPutHere{
self.blink()
}
}
我认为.autoreverse选项会将其恢复为原始颜色。当然,这将只是一次闪烁,但我要实现重复,一旦我设法让它闪烁一次。你能告诉我打电话的正确位置吗?你需要等到这个手机显示出来cellForRowAt
只是一个关于单元格应该是什么的查询。你不能为视图层次结构中不存在的东西设置动画。好的,马特,我想我找到了一种方法。谢谢您的时间……是的,您现在正在等待,将显示
。这绝对是一种方法。仔细检查shouldBlink
——记住单元格是重复使用的,因此确保您的逻辑考虑到了这一点。闪烁并不与单元格本身有关,而是与它在表视图中所假定的位置有关。谢谢。我会处理的