我正在为UIImageView创建子类,因此每次设置图像属性时都会发生动画.以下是成功的:
import UIKit class AnimatedImageView: UIImageView { var img: UIImage! { get { return self.image } set { self.image = newValue UIView.animateWithDuration(0.5, delay: 0.4, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: .CurveEaseIn, animations: {_ in self.transform = CGAffineTransformMakeScale(1.1, 1.1); }, completion: {_ in self.transform = CGAffineTransformIdentity; }) } }
这并不奇怪.我将UIImageView子类化并添加了一个名为'img'的全新变量,该变量又修改了UIImageView的'image'属性.
问题是最终用户可能会改变AnimatedImageView的'image'属性.
import UIKit class AnimatedImageView: UIImageView { override var image: UIImage! { get { return self.image } set { self.image = newValue UIView.animateWithDuration(0.5, delay: 0.4, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: .CurveEaseIn, animations: {_ in self.transform = CGAffineTransformMakeScale(1.1, 1.1); }, completion: {_ in self.transform = CGAffineTransformIdentity; }) } }
果然这会导致堆栈溢出,因为当我self.image = newValue
重复调用它时,会调用我在子类中重写的setter方法.那么,在UIImageView上覆盖'image'属性的getter/setter方法的正确方法是什么
只需使用super.image
,这将阻止循环.