I want to add variables in the extension of the UIView

Asked 2 years ago, Updated 2 years ago, 37 views

As per the title, when I looked into it to implement it, I found an article saying that Extensions can add methods, but not variables, and it said that I had to add classes myself.But I don't know how to do it.

swift ios

2022-09-30 18:33

2 Answers

If you write down what you want to achieve using the variable rather than simply "I want to add a variable", you may get a more accurate answer that suits your purpose.

"When you say ""you have to add your own class"" that was investigated, I think you are referring to subclassification."

class MyView:UIView{
    var myInt —Int=0
    var myString: String?=nil
}

If you create a class that inherits UIView in this way (replace the name MyView with a more appropriate name for the real app), you can use instances of the UIView class as a type of UIView.

However, there are many difficulties in subclassing UIView, and even quite a few experienced developers often struggle.As I wrote at the beginning, if you could explain "what you really want to do" without sticking to a particular methodology, you might find a much simpler and better solution.


2022-09-30 18:33

Can be accomplished using Associated Objects

var hogeKey:UInt8=0

extension UIView {
    varhoge:String?{
        get{
            guard let object = objc_getAssociatedObject(self, & hogeKey) as ? String else {
                return nil
            }
            return object
        }
        set {
            objc_setAssociatedObject(self, & hogeKey, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }
}


2022-09-30 18:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.