简体   繁体   English

KVO 检查目标 c 中 UIView 中所有子视图的 clipsToBounds 的变化

[英]KVO check for change of clipsToBounds of all subviews in an UIView in objective c

I am trying to implement a KVO example for clipsToBounds property of all subviews in my UIView.我正在尝试为我的 UIView 中所有子视图的 clipsToBounds 属性实现一个KVO示例。 I do not quite understand how to change the value in observeValueForKeyPath method.我不太明白如何更改 observeValueForKeyPath 方法中的值。 I am using this code:我正在使用这段代码:

-(void)ViewDidLoad{
        [self.navigationController.view addObserver:self forKeyPath:@"clipsToBounds" options:NSKeyValueObservingOptionNew |
         NSKeyValueObservingOptionOld context:nil];
    }
    
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"Triggered...")
    }

It is triggered when ever i change the property clipToBounds of a subview that exists in the UIView i have.当我更改存在于 UIView 中的子视图的属性 clipToBounds 时,它会被触发。 I need to change the value back to false for every trigger that happens.对于发生的每个触发器,我都需要将值更改回 false。 What should i write inside the observeValueForKeyPath to change the clipsToBounds property?我应该在 observeValueForKeyPath 中写什么来更改 clipsToBounds 属性? Any help appreciated.任何帮助表示赞赏。

of course adding the Observer must be done before it works.当然,添加观察者必须在它起作用之前完成。 Guessing your typo in "ViewDidLoad" would just never be called because it should be "viewDidLoad".永远不会调用您在“ViewDidLoad”中的拼写错误,因为它应该是“viewDidLoad”。 Apart from that your KVO pattern could look like..除此之外,您的 KVO 模式可能看起来像..

static void *kvoHelperClipsToBounds = &kvoHelperClipsToBounds;

-(void)viewDidLoad {
    [self.navigationController.view addObserver:self forKeyPath:@"clipsToBounds" options:NSKeyValueObservingOptionNew context:kvoHelperClipsToBounds];
}
    
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kvoHelperClipsToBounds) {
        NSLog(@"context compare Triggered...");
    } 

    // or compare against the keyPath
    else if ([keyPath isEqualToString:@"clipsToBounds"]) {
        NSLog(@"classic Key compare Triggered...");
    }
    else
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

Sidenote: the context just needs to be unique to distinguish it from other KVO.. it could also be reference to a real objects pointer.旁注:上下文只需要唯一即可将其与其他 KVO 区分开来。它也可以是对真实对象指针的引用。

Don't forget added Observers must be removed before deallocation.不要忘记添加的观察者必须在释放之前被移除。

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

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