我有一个UITableView,其中每一行都是自定义XIB。一行有4个UIButton,它们是选项,如问题,信息等。当点击UIButton时,我在CALayer中显示动画。当表格视图滚动时,CALayer被删除,即动画消失了。
点击按钮时,我会打开CALayer并开始动画。当滚动或更新表格时,如何确保CALayer不会消失?
class ReasonForSupportTableViewCell: UITableViewCell {
let animationView = AnimationView()
var hasButtonBeenTapped = false
var previousButtonTapped: UIButton? = nil
//IBOutlets
@IBOutlet weak var questionButton: UIButton!
@IBOutlet weak var informationButton: UIButton!
@IBOutlet weak var crashButton: UIButton!
@IBOutlet weak var bugButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
//set initial button
questionButton.sendActions(for: .touchUpInside)
}
func createView(sender: UIButton) {
//draw the frame
animationView.frame = CGRect(x: 0, y: 0, width: 75.0, height: 75.0)
//change the view background color
animationView.backgroundColor = UIColor.clear
animationView.isUserInteractionEnabled = false
//add the view.
sender.addSubview(animationView)
}
@IBAction func buttonTapped(_ sender: UIButton) {
if previousButtonTapped == nil {
//you haven't tapped a button yet
createView(sender: sender)
animationView.animateTo()
previousButtonTapped = sender
} else if previousButtonTapped == sender {
animationView.removeAnimation()
previousButtonTapped = nil
} else {
animationView.removeAnimation()
createView(sender: sender)
animationView.animateTo()
previousButtonTapped = sender
}
}
}
子类UIButton在初始化时添加CALayer,而不是在点击按钮时添加。然后,您可以使用prepareForReuse()
函数来停止任何动画。