我已经搜索了这个问题的答案,但我找到的答案都不起作用。
我有一个视图,它是我添加了属性的UIView的子类。我想从这个视图创建的子视图中访问这个属性。这有可能吗?
我曾尝试引用self.superview.propertyname,但得到一个错误,即在类型为UIView的对象上找不到属性名。好吧,好吧。我意识到既然它是UIView的子类,它就是一个UIView,但是我怎样才能让它知道我添加的额外属性呢?
发布于 2012-06-23 11:00:36
您有许多选项,其中两个是:
1.造型:
@implementation SubviewView
- (void)blah
{
((CustomView *)self.superview).property = ...`
}
@end2.委派:
@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虽然第二种选择是更多的代码,但我认为它通常更适合。使用委托可以减少耦合,并且可以很好地与Law of Demeter配合使用。有关更多信息,请参阅此documentation。
https://stackoverflow.com/questions/11166399
复制相似问题