我有一个 UIView 子类,它又有一个 contentView,在公共(public) header 中这样声明:
@property (nonatomic,retain)UIVivew* contentView;
我试图在 contentView 的框架发生变化时获取 KVO 通知,但我的 UIView 子类中从未调用过 observeValueForKeyPath 方法:
@implementation MyView
@synthesize contentView = _contentView;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self.contentView addObserver:self
forKeyPath:@"frame"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:nil];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"frame"]) {
CGRect newContentFrame = [[change objectForKey:NSKeyValueChangeNewKey] CGRectValue];
CGRect selfNewFrame = self.frame;
selfNewFrame.size = CGSizeMake(newContentFrame.size.width + 10, newContentFrame.size.height + 10);
self.frame = selfNewFrame;
}
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
关于为什么 KVO 没有触发的任何想法?
最佳答案
抱歉...我猜 sleep 不足...
忘记分配/初始化 contentView。
关于ios - 为什么 KVO 不能在 UIView 子类上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910007/