Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to add new property to UIImageView class?

I'm afraid I'm relatively new to Swift, but have looked around as best I could and haven't been able to figure out how to do this relatively simple task!

I would like to add a new property called "angle" to the class UIImageView, such that you could use "image.angle". Here's what I've got, having attempted to follow the method of a tutorial I used (note that the required init? part was suggested by Xcode and I am not too sure of what it does):

class selection_image: UIImageView {

    var angle = Double()

    init(angle: Double) {
        self.angle = angle
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Thank you very much for any help!!

like image 904
jasperthedog Avatar asked Oct 19 '25 06:10

jasperthedog


2 Answers

class selection_image: UIImageView {

    var angle = Double()

    // your new Init
  required convenience  init(angle: Double) {
        self.init(frame: CGRect.zero)

        self.angle = angle
    }

    override init(frame: CGRect) {
        super.init(frame: CGRect.zero)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
like image 58
Abdelahad Darwish Avatar answered Oct 21 '25 20:10

Abdelahad Darwish


Using Swift 4.2

@jasperthedog. You can add a property to a given class using AssociatedObjects of the Runtime using an extension as follows:

In this example, I add an optional viewAlreadyAppeared: Bool? property to UIViewController. And with this, I avoid creating subclasses of UIViewController

extension UIViewController {
    private struct CustomProperties {
        static var viewAlreadyAppeared: Bool? = nil
    }
    var viewAlreadyAppeared: Bool? {
        get {
            return objc_getAssociatedObject(self, &CustomProperties.viewAlreadyAppeared) as? Bool
        }
        set {
            if let unwrappedValue  = newValue {
                objc_setAssociatedObject(self, &CustomProperties.viewAlreadyAppeared, unwrappedValue as Bool?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}
like image 33
eharo2 Avatar answered Oct 21 '25 21:10

eharo2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!