[英]insert a xib as a subview, then add a subview from that xib over the parent view
[英]Using a XIB's view as subview and access its textfield property
我正在嘗試使用NameSubView
的NameSubViewController
作為MainViewController
的子視圖。 我做了那個工作,但我也想訪問子視圖的UITextField
,如下所示:
MainViewController.m :
#import "NameSubViewController.h"
...
UIViewController *nameController = [[NameSubViewController alloc] initWithNibName:@"NameSubViewController" bundle:nil];
nameSubView = [nameController view];
[self.view addSubview:nameSubView];
NSString *textFieldString = nameSubView.textField.text;
但我無法使其正常工作。 這就是我創建子視圖時所做的:
使用XIB制作NameSubViewController
類用於接口
為IB視圖NameSubView
類,將視圖設置為此類Identity Inspector
創建@property (nonatomic, strong) IBOutlet UITextField *textField;
在NameSubView
並連接到IB中的文本字段。
然后我可以加載子視圖,但我無法從MainViewController
訪問textField。 因此,為了訪問它,我確實將NameSubView
中的Files Owner的類 NameSubViewController
為Identity Inspector中的NameSubView
。
現在訪問NameSubViewController
,但沒有找到視圖的屬性,因此應用程序崩潰。 我不知道如果我下面的正確的程序,我現在可以創建的屬性NameSubView
在NameSubViewController
? 或者我應該遵循另一個程序?
NameSubViewController
返回到身份檢查器中的文件所有者。 NameSubView
添加到身份檢查器中的視圖。 然后使用此代碼:
#import "NameSubViewController.h"
// If view's declaration is located in a separate file then the next line is important
#import "NameSubView.h"
...
// It is better to declare the view controller as 'NameSubViewController'
NameSubViewController *nameController = [[NameSubViewController alloc] initWithNibName:@"NameSubViewController" bundle:nil];
// A casting to 'NameSubView' should do the main magic
NameSubView *nameSubView = (NameSubView *)[nameController view];
[self.view addSubview:nameSubView];
// It is better to ensure that the view is of a correct class
// before using its specific properties
if ([nameSubView isKindOfClass:[NameSubView class]]) {
// Now it should work
// (assuming that you have a property 'textField' in 'NameSubView')
NSString *textFieldString = nameSubView.textField.text;
}
首先,將文件的所有者更改回NameSubViewController
。 將文本字段IBOutlet聲明移動到NameSubViewController,並確保在nib中正確連接所有內容。 最后,將nameController
變量聲明為NameSubViewController
而不是UIViewController。 然后,您應該能夠使用nameController.textField
獲取文本nameController.textField
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.