Nijat2018
Nijat2018

Reputation: 873

Xcode how to detect a view's properties changed?

How can I detect a view's x,y,width or height is changed ?

I want to implement that once a view's properties are changed, the other view's positions are reorganised.

For example, I have a webview which has dynamic height. Each time webViewDidFinishLoad I will change the height of webView, then the other view's position will be changed according webview.frame.

I have been thinking i change all the view's position inside the delegate function webViewDidFinishLoad. But i have too many views.

I want to know if I can implement this behaviour using " Key-Value Observing "

If i can, how to implement it.

Upvotes: 0

Views: 1007

Answers (2)

Reming Hsu
Reming Hsu

Reputation: 2225

//added KVO for webview
[webview addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionOld context:NULL];  

//when observer changed would call:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString:@"frame"]) {
        //do something
        NSLog(@"new:%@",[change objectForKey:NSKeyValueChangeNewKey]);
        NSLog(@"old:%@",[change objectForKey:NSKeyValueChangeOldKey]);
    }
}

//when you don't need kvo, remove observer
[webview removeObserver:self forKeyPath:@"frame"];

keyPath
The key path, relative to the receiver, of the property to observe. This value must not be nil.

change
A dictionary that describes the changes that have been made to the value of the property at the key path keyPath relative to object.

Upvotes: 1

Nghia Luong
Nghia Luong

Reputation: 790

You can use Delegate or NSNotificationCenter to push value to controller which is holding other views.

Hope this could help.

Upvotes: 0

Related Questions