我想为 UITableViewCell 添加波纹效果,类似于此链接 https://raw.githubusercontent.com/bfeher/BFPaperTableViewCell/master/BFPaperTableViewCellDemoGif.gif .有很多 pod 可用,但我想了解如何完成此类动画。我在 didHighlightRowAt 委托(delegate)中添加了几行代码来执行波纹动画,但动画没有发生。 这是我到目前为止所做的代码
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)!
cell.contentView.subviews.forEach { (view) in
view.layer.masksToBounds = true
print(view.layer.cornerRadius)
let startAnimation = UIBezierPath(rect: CGRect(x: view.bounds.origin.x, y: view.bounds.origin.y, width: view.bounds.width, height: view.bounds.height)).cgPath
let endAnimation = UIBezierPath(rect: CGRect(x: view.bounds.width, y: view.bounds.origin.y, width: view.bounds.width, height: view.bounds.height)).cgPath
let shapeLayer = CAShapeLayer()
let compinedLayer = CGMutablePath()
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.cornerRadius = 10.0
shapeLayer.opacity = 0.5
let animation = CABasicAnimation(keyPath: "ripple")
animation.fromValue = startAnimation
animation.toValue = endAnimation
animation.duration = 3
animation.fillMode = CAMediaTimingFillMode.both
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
animation.isRemovedOnCompletion = false
compinedLayer.addPath(startAnimation)
compinedLayer.addPath(endAnimation)
shapeLayer.path = compinedLayer
view.layer.insertSublayer(shapeLayer, at: 0)
shapeLayer.add(animation, forKey: "ripple")
let deatline = DispatchTime(uptimeNanoseconds: UInt64((3 * 0.75)) * NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: deatline, execute: {
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fillMode = CAMediaTimingFillMode.both
opacityAnimation.duration = 3 - (3 * 0.75)
opacityAnimation.fromValue = endAnimation
opacityAnimation.toValue = startAnimation
opacityAnimation.isRemovedOnCompletion = false
shapeLayer.add(opacityAnimation, forKey: "opacity")
})
let deadline = DispatchTime(uptimeNanoseconds: UInt64(3 - (3 * 0.75)))
DispatchQueue.main.asyncAfter(deadline: deadline, execute: {
shapeLayer.removeAllAnimations()
shapeLayer.removeFromSuperlayer()
})
}
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return true
}
最佳答案
我还没有运行代码,但第一个明显的问题是不透明度动画。 from 和 toValues 需要是从 1 到 0 的数字,我相信您正在添加用于 shapelayer 的路径。其次,您可以使用 CATransactions 和完成 block ,而不是使用所有调度时间。对于任何延迟,请使用 beginTime 属性。希望这可以帮助。这是一个类似的问题,因此您可以查看我的代码。 Material Ripple Effect for UICollectionView Cell .我注意到的其他一些事情是在第一次点击您发布的视频时,它似乎在图像上也放置了波纹的 CATransition 以使其也扭曲。老实说,在解构动画时,我会记录它们并慢慢地擦洗它们。还有一些关于 CALayer 的很棒的资源。祝你好运,学习它非常强大。
关于ios - 突出显示表格 View 单元格时显示波纹效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247623/