I simply want to flash a red border around a UIView then fade out to clear, repeatedly. However, the UIView animate method doesn't seem to work.
Is there something special about the layer that prevent UIView animate from working?
public class MyAlertView: UIView {
convenience init(args: [String]) {
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.translatesAutoresizingMaskIntoConstraints = false
self.layer.cornerRadius = 10
self.layer.borderColor = UIColor.systemRed.cgColor
self.layer.borderWidth = 2.5
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseInOut, .repeat, .autoreverse], animations: {
self.layer.borderColor = UIColor.clear.cgColor
})
}
}
To animate layers need to use CAAnimations u can use this extension
extension CALayer {
func addLoopBorderAnimation(from startColor: UIColor, to endColor: UIColor, withDuration duration: Double) {
let colorAnimation = CABasicAnimation(keyPath: "borderColor")
colorAnimation.fromValue = startColor.cgColor
colorAnimation.toValue = endColor.cgColor
colorAnimation.duration = duration
colorAnimation.repeatCount = .greatestFiniteMagnitude
colorAnimation.autoreverses = true
self.borderColor = endColor.cgColor
self.add(colorAnimation, forKey: "borderColor")
}
}
and call
private func commonInit() {
self.translatesAutoresizingMaskIntoConstraints = false
self.layer.cornerRadius = 10
self.layer.borderColor = UIColor.systemRed.cgColor
self.layer.borderWidth = 2.5
self.layer.addLoopBorderAnimation(from: UIColor.systemRed, to: UIColor.clear, withDuration: 0.5
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.