繁体   English   中英

iOS:将观察者添加到UIView的frame.origin.y?

[英]iOS: Adding observer to a UIView's frame.origin.y?

我正在试图监视和回应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永远不会被调用。 我猜对帧起源的改变不算作对帧的改变..?

如何完成向UIView的frame.origin.y添加观察者?

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

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

使用ReactiveCocoa非常简单:

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

例如。

我认为不可能只观察框架的y值。 但是,您可以覆盖setFrame:方法而不是观察frame属性

像这样:

- (void)setFrame:(CGRect)frame 
{
    [super setFrame:frame]
    if (self.frame.origin.y != frame.origin.y){
         // Do your stuff here
    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM