我试图让我的viewcontroller
(PersonalListViewController
)加载UITableView
。页面底部有一个addPersonalItem
按钮。当用户按下按钮时,它将从Nib文件中加载UIView
(AddItemView
)。
在AddItemView
上有两个UITextFields
。 1)我如何才能从PersonalListViewController
中访问在字段中输入的文本,以及2)当用户从屏幕上删除PersonalListViewController
时(即在AddItemView
上输入文本并按Done),如何知道AddItemView
?
在PersonalListViewController.m中
- (IBAction)addPersonalItem:(id)sender {
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"AddItemView" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self.view addSubview:mainView];
}
在AddItemView.h中
#import <UIKit/UIKit.h>
@interface AddItemView : UIView {
IBOutlet UITextField *itemNameTextField;
IBOutlet UITextField *quantityTextField;
}
@property (strong, nonatomic) IBOutlet UITextField *itemNameTextField;
@property (strong, nonatomic) IBOutlet UITextField *quantityTextField;
@end
在AddItemView.m中
#import "AddItemView.h"
@implementation AddItemView
@synthesize itemNameTextField;
@synthesize quantityTextField;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
最佳答案
试试这个,
通过AddItemView
定义一个块
typedef void (^completionBlock)(NSString *itemName, NSString *quantity);
添加此块的属性
@property (nonatomic, strong) completionBlock completionCallback;
所以,在
AddItemView.h
#import <UIKit/UIKit.h>
typedef void (^completionBlock)(NSString *itemName, NSString *quantity);
@interface AddItemView : UIView {
IBOutlet UITextField *itemNameTextField;
IBOutlet UITextField *quantityTextField;
}
@property (strong, nonatomic) IBOutlet UITextField *itemNameTextField;
@property (strong, nonatomic) IBOutlet UITextField *quantityTextField;
@property (nonatomic, strong) completionBlock completionCallback;
- (IBAction)completionButtonAction:(id)sender;
@end
在
UIButton
中添加一个AddItemView
,并在其中执行一个类似于- (IBAction)completionButtonAction:(id)sender {
if (self.completionCallback != nil) {
NSString *itemName = self.itemNameTextField.text;
NSString *quantity = self. quantityTextField.text;
self.completionCallback (itemName, quantity);
}
}
在PersonalListViewController.m中
- (IBAction)addPersonalItem:(id)sender {
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"AddItemView" owner:self options:nil];
AddItemView *mainView = (AddItemView *)[subviewArray objectAtIndex:0];
void (^completionBlock)(NSString *itemName, NSString *quantity) = ^(NSString *itemName, NSString *quantity){
[self personalItemAddedWithItemName:itemName quantity:quantity];
};
mainView.completionCallback = completionBlock
[self.view addSubview:mainView];
}
- (void)personalItemAddedWithItemName:(NSString *)itemName quantity:(NSString *)quantity {
//add your code here
}
关于ios - 访问从Nib加载的 subview 中的文本字段中的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21104877/