我想在我的应用程序中使用KVO。我有一个类属性sizeForScrollView,当这个属性改变时我想要通知。我试了但是没用。这是代码:
[self.aSubjectView addObserver:self forKeyPath:@"sizeForScrollView" options:NSKeyValueObservingOptionNew context:NULL];
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
self.scrollView.contentSize = CGSizeMake(self.aSubjectView.sizeForScrollView.width, self.aSubjectView.sizeForScrollView.height);
self.aSubjectView.frame = CGRectMake(frameForView.origin.x, frameForView.origin.y, frameForView.size.width, self.aSubjectView.sizeForScrollView.height);
}
答案 0 :(得分:1)
self.aSubjectView必须初始化,并且在添加观察者时不能为零。
在observeValueForKeyPath中的你当前正在检查self.aSubjectView是否已初始化,但你应该检查
if (object == self.aSubjectView)
试
[self.aSubjectView addObserver:self forKeyPath:@"sizeForScrollView" options:NSKeyValueObservingOptionNew context:NULL];
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if (object == self.aSubjectView) {
self.scrollView.contentSize = CGSizeMake(self.aSubjectView.sizeForScrollView.width, self.aSubjectView.sizeForScrollView.height);
self.aSubjectView.frame = CGRectMake(frameForView.origin.x, frameForView.origin.y, frameForView.size.width, self.aSubjectView.sizeForScrollView.height);
}
}