0

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.

Wez
  • 10,555
  • 5
  • 49
  • 63
Nijat2018
  • 863
  • 2
  • 10
  • 26

2 Answers2

1
//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.

Reming Hsu
  • 2,215
  • 15
  • 18
0

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

Hope this could help.

Nghia Luong
  • 790
  • 1
  • 6
  • 11