Overriding the getter / setter methods of UIImageView images

I will subclass UIImageView so that every time an image property is set, animation happens. The following has been completed:

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; }) } } 

This is not surprising. I subclassed UIImageView and added a brand new variable called "img", which in turn changes the image property of UIImageView.

The problem is that the end user can apparently still modify the AnimatedImageView 'image' property.

 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; }) } } 

Of course, this calls stackoverflow, because when I call self.image = newValue , it repeatedly calls the setter method, which I redefined in my subclass. So what is the right way to override the getter / setter methods of the image property in a UIImageView

+5
source share
2 answers

Just use super.image instead to prevent a loop.

+6
source

An alternative to using super.image would be to link to the image using ivar _image. This directly refers to it without causing a getter, and avoids the loop.

 import UIKit class AnimatedImageView: UIImageView { override var image: UIImage! { get { return _image } set { _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; }) } 
0
source

Source: https://habr.com/ru/post/1237287/


All Articles