我的动态编号UITextFields
都有inputAccessoryView
。它由UIToolbar
组成,其上有一个按钮。按下此按钮时,它会调用一个方法,但是,在此方法中,我需要能够访问基础UITextField
。
请有人可以告知如何做到这一点吗?
// Create the toolbar controls
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(navigationBarDoneButtonPressed:)];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
// Setup the toolbar
navigationToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(10.0, 0.0, 310.0, 40.0)];
[navigationToolbar setItems:@[flexibleSpace, doneButton]];
// In a UITableView I create a number of cells which contain UITextFields....
// This is the method that gets called when a user presses the done button
- (void)navigationBarDoneButtonPressed:(id)sender
{
NSLog(@"Based on sender I need to access the underlying UITextField.");
}
答案 0 :(得分:6)
您可以跟踪变量中当前关注的UITextField
,并在inputAccesoryView
方法中使用该变量:
:确保你符合UITextFieldDelegate
协议:
@interface MyViewController : UIViewController <UITextFieldDelegate>
并添加此属性:
@property (assign, nonatomic) UITextField *activeTextField;
在.m文件中:创建动态文本字段时:
...
theTextField.delegate=self;
...
并添加UITextFieldDelegate
协议的这些实现:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.activeTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
self.activeTextField = nil;
}
现在,在inputAccesoryView
:
- (void)navigationBarDoneButtonPressed:(id)sender{//Just an example
self.activeTextField.text=@"Test";
}
答案 1 :(得分:0)
我将使用委托创建UITableViewCell子类,例如
MyTextEditTableViewCell.h
@class MyTextEditTableViewCell;
@protocol MyTextEditTableViewCellDelegate <NSObject>
- (void)didDoneButtonPressed:(MyTextEditTableViewCell *)sender;
@end
@interface MyTextEditTableViewCell : UITableViewCell
@property (nonatomic, weak) id<MyTextEditTableViewCellDelegate> delegate;
@property (nonatomic, strong) UITextField *textField;
@end
MyTextEditTableViewCell.m
@implementation MyTextEditTableViewCell
- (void)navigationBarDoneButtonPressed:(id)sender
{
// Call delegate
if (self.delegate)
[self.delegate didDoneButtonPressed:self];
}
@end
您的UIViewController子类(或UITableViewController)
...
- (void)didDoneButtonPressed:(MyTextEditTableViewCell *)sender {
UITextField *cellTextField = sender.textField;
// do some stuff with text field
}
在配置时,不要忘记将委托设置为单元格。