iOS:如何向UIView的frame.origin.y添加观察者?

11

我试图监测并对UIView框架的起点值进行反应。我的代码:

[cell.bottomView addObserver:self forKeyPath:@"frame.origin" options:NSKeyValueObservingOptionNew context:NULL];

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@ Changed", keyPath);
}
我收到了一个我不理解的错误信息:
An instance 0x7587d10 of class NSConcreteValue was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info:
<NSKeyValueObservationInfo 0x7587fd0> (
<NSKeyValueObservance 0x7587f70: Observer: 0x7587bd0, Key path: origin, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x7587ff0>
)

实际上,我只对原点的y位置感兴趣,但是如果我将keyPath设置为"frame.origin.y",代码甚至无法编译。

如果我将keyPath简单地设置为"frame",就没有错误,但是observeValueForKeyPath方法从未被调用。我猜改变frame的原点位置不算作对frame的更改..?

如何添加观察者以获取UIView的frame.origin.y值?


你的 observerValueForKeyPath: 方法中没有调用 super。 - pronebird
3个回答

11

虽然我无法以最初想要的方式完全解决我的问题,但我发现我能够正确地将观察者添加到UIView的中心。 通过监视视图的中心,我可以确定该框架的起点已更改。

[cell.bottomView addObserver:self forKeyPath:@"center" options:NSKeyValueObservingOptionNew context:NULL];

5

使用 ReactiveCocoa 很简单:

[RACObserve(self.view, frame) subscribeNext:^(NSNumber *rect) {
        NSLog(@"position y: %f", rect.CGRectValue.origin.y);
    }];

例如。

2
我认为不可能仅观察帧的y值。但是,你可以重写setFrame:方法,而不是观察frame属性。
像这样:
- (void)setFrame:(CGRect)frame 
{
    [super setFrame:frame]
    if (self.frame.origin.y != frame.origin.y){
         // Do your stuff here
    }
 }

谢谢您的建议。我尝试了一下,但是这种方法似乎没有被调用。问题在于,我正在使用自动布局,在某个时刻(不确定是什么时候,但是当容器视图到达didMoveToWindow时)修改了frame.origin.y。您是否知道自动布局使用哪种方法来修改框架? - Sethypie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接