我有一個自定義的容器導航。我有一個日記視圖控制器和一個日記詳細視圖控制器。當用戶點擊日記中的圖片時,使用cycleFromViewController:toViewController
方法進入日記詳細信息,如Apple文檔中關於容器視圖控制器所述。observeValueForKeyPath多次調用
當詳細視圖加載時,我希望容器視圖控制器刪除它的一個子視圖並添加另一個子視圖。我使用KVC來完成這個任務。這是我第一次使用KVC。 addObserver
方法是在viewWillAppear
的日記詳細vc。
問題:加載日誌細節VC,第一次調用observeValueForKeypath
,第二次調用observeValueForKeypath
,依此類推。此外,在observeValueForKeypath
中,我添加了一個子視圖--UIButton - 當它被點擊時,cycleFromViewController:toViewController
被再次調用,並且之前的子視圖被添加回來。它可以在第一時間工作,但在後續的工作中,原始的子視圖不會被添加回來,UIButton只是停留在周圍。
日記Detail.m
-(void)viewWillAppear:(BOOL)animated{
[self addObserver:self.parentViewController forKeyPath:@"didLoadNumber" options:0 context:nil];
[self setValue:[NSNumber numberWithInt:0] forKey:@"didLoadNumber"];}
主要集裝箱VC(觀察者/父VC)
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"KVO called");
[self.usernameLabel removeFromSuperview];
self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(12, 28, 28, 28)];
self.backButton.backgroundColor = [UIColor blackColor];
[self.view addSubview:self.backButton];
[self.backButton addTarget:self action:@selector(removeButtonAndAddLogo)
forControlEvents:UIControlEventTouchUpInside];
}
-(void)removeButtonAndAddLogo{
NSLog(@"got to remove button");
[self.backButton removeFromSuperview];
self.usernameLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 28, 28, 28)];
self.usernameLabel.text = @"username";
self.usernameLabel.textColor = [UIColor blackColor];
[self.view addSubview:self.usernameLabel];
[self cycleFromViewController:self.diaryViewController.diaryDetailVC toViewController:self.diaryViewController];
}