Reputation: 2133
I've searched for the answer to this question, and the answers I'm finding don't work.
I have a view that is a subclass of UIView to which I've added a property. I would like to access this property from the subviews created by this view. Is that possible?
I've tried referring to self.superview.propertyname but I get an error that propertyname is not found on object of type UIView. Well, right. I realize that since it's a subclass of UIView, it's a UIView, but how can I get it to know about the extra property I added?
Upvotes: 0
Views: 2371
Reputation: 38062
You have a number of options, two of them are:
1. Casting:
@implementation SubviewView
- (void)blah
{
((CustomView *)self.superview).property = ...`
}
@end
2. Delegates:
@protocol SubviewViewDelegate
- (void)customView:(SubView *)sv modified:(...)value;
@end
@class SubView
@property (nonatomic, weak) id <CustomViewDelegate> delegate;
@end
@implementation SubviewView
- (void)blah
{
[self.delegate subView modified:...];
}
@end
@implementation CustomView
- (void)subView:(SubView *)sv modified:(...)value
{
self.property = value;
}
@end
Although the second option is more code, I think it is often better suited. Using delegates reduces coupling and works nicely with the Law of Demeter. For more info see this documentation.
Upvotes: 2