簡體   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