我正在嘗試為UIView 中所有子視圖的 clipsToBounds 屬性實作一個KVO示例。我不太明白如何更改observeValueForKeyPath 方法中的值。我正在使用此代碼:
-(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...")
}
當我更改 UIView 中存在的子視圖的屬性 clipToBounds 時,就會觸發它。對于發生的每個觸發器,我都需要將值改回 false。我應該在observeValueForKeyPath里面寫什么來改變clipsToBounds屬性?任何幫助表示贊賞。
uj5u.com熱心網友回復:
當然添加觀察者必須在它作業之前完成。猜測您在“ViewDidLoad”中的錯字永遠不會被呼叫,因為它應該是“viewDidLoad”。除此之外,您的 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 compared successful...");
//be careful what you cast to.. i dont check isKindOf here.
UINavigationBar* navbar = (UINavigationBar*)object;
if (navbar.subviews.count > 1) {
__kindof UIView *sub = navbar.subviews[1];
if (sub.clipsToBounds) {
dispatch_async(dispatch_get_main_queue(),^{
sub.clipsToBounds = NO;
[self.navigationItem.titleView layoutIfNeeded];
});
}
}
}
// 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];
}
[super observeValueForKeyPath...]將無法識別的 keyPath 傳遞給super以讓 super 的類 KVO 作業,否則如果 super 的實作依賴于觀察它們,這些將被忽略。如果需要,這還應該解釋如何觀察所有子視圖。但是考慮一下,如果 UIView 的子類實作它并且所有子視圖(或您喜歡的子視圖)也將從這個特殊的子類繼承,那么可能會有很多子視圖觸發observeValueForKeyPath。
當您在觀察 KVO 的地方更改clipsToBounds時,您可能會呼叫一個回圈,特別是當您同時查看舊值和新值時。你會改變屬性,屬性觸發 kvo,kvo 改變屬性,屬性觸發 kvo 等等。
設定[self.navigationController.view setClipsToBounds:YES]更改屬性。但是如果在 KVO 內部完成,它將按照解釋再次觸發 KVO。通常,您會在Interface Builder中或中或通過 Interface Builder設定clipsToBounds,也許只是觀察它是否被更改以適應其他一些代碼。-initWithFrame:-initWithCoder:
旁注:背景關系只需要唯一即可將其與其他 KVO 區分開來。它也可以是對真實物件指標的參考。
不要忘記在釋放之前必須洗掉添加的觀察者。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/393991.html
