簡體   English   中英

如何將 XIB 子代的 UIView 與父 XIB 的 UIView 通信?

[英]How to communicate an UIView from a XIB child to an UIView from a parent XIB?

我想知道是否可以在從 XIB 文件加載的 UIView 內點擊某處(或做其他事情)並從父 XIB 觸發 UIView 的操作(例如更改父 UIC 中 ZA4F6654A7772842B01988CBFEC 的標題)。 這是NewsController class接口的代碼片段:

#import <UIKit/UIKit.h>
#import "NewsPage.h"
@interface NewsController : UIViewController {
    // Some objects
    UIButton *loadButton;
    UIView *newsView;
    NewsPage *newsPage;
}
@property (nonatomic, retain) IBOutlet UIButton *loadButton;
@property (nonatomic, retain) IBOutlet UIView *newsView;
@property (nonatomic, retain) NewsPage *newsPage;
@end

這是 NewsPage 的 class 實現的片段,我在其中加載子 XIB:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Some code
    newsPage = [[NewsPage alloc] initWithNibName:@"NewsPage" bundle:nil];
    [newsView addSubview:newsPage.view];
    // Some other code
}

這是 NewsPage class 接口內的一段代碼:

#import <UIKit/UIKit.h>
#import "NewsController.h"
@interface NewsPage : UIViewController {
    NewsController *newsController;
}
@property (nonatomic, retain) IBOutlet NewsController *newsController;
@end

這是 class 實現的片段

- (void)tapAction:(UIGestureRecognizer *)gestureRecognizer {
    // Some code
    NewsController *newsController = [[NewsController alloc] initWithNibName:@"News" bundle:nil];
    NSLog(@"Current button title is: %@\n", newsController.loadButton.titleLabel.text);        
    newsController.loadButton.titleLabel.text = @"New text goes here!";
    NSLog(@"Current button title is: %@\n", newsController.loadButton.titleLabel.text);
    // Some other code
}

使用此代碼(並在 IB 中進行一些接線之后),我在調試器中看到了正確的標題,但模擬器不會更新標題更改。 我的猜測是子 UIViews 與父 UIViews 平行,即使我做了這樣的事情:

[newsController.loadButton removeFromSuperview]

父 UIView 層次結構沒有變化,因為子 UIViews “不在”父 UIView 的“內部”。 我希望有人可以幫助解決這個問題,因為這非常令人沮喪。 在此先感謝您。

我看到的一個問題是,您正在訪問 NewsController 中的一些元素,這些元素可能尚未從 NIB 中解壓縮,因為它們在需要視圖時是懶惰地完成的。 在引用這些項目之前,嘗試訪問 controller 的 .view 成員,這應該強制加載。 這是一個似乎每個人都會遇到的問題,直到延遲加載的想法被理解。

NewsController *newsController = [[NewsController alloc] initWithNibName:@"News" bundle:nil];
newController.view; //hopefully this doens't get optimized out. If so, change it a bit.
NSLog(@"Current button title is: %@\n", newsController.loadButton.titleLabel.text);   

本質上,當父母想知道孩子會告訴它的事情時,您在孩子上設置一個委托作為父母,然后在孩子代碼中您首先檢查該委托是否存在,然后確保它響應您將發送的選擇器。 然后你向它發送一條消息。

通過使用@protocol 來實現這一點的好方法

這是一個包含一些基本信息的鏈接

http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM