簡體   English   中英

使用XIB的視圖作為子視圖並訪問其textfield屬性

[英]Using a XIB's view as subview and access its textfield property

我正在嘗試使用NameSubViewNameSubViewController作為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 ,但沒有找到視圖的屬性,因此應用程序崩潰。 我不知道如果我下面的正確的程序,我現在可以創建的屬性NameSubViewNameSubViewController 或者我應該遵循另一個程序?

  • 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.

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