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.
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)
}
}
}
© 2024 OneMinuteCode. All rights reserved.