[英]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.