6

我有一个动态编号,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.");
}
4

2 回答 2

7

您可以跟踪当前关注UITextField的变量,并在您的inputAccesoryView方法中使用该变量:

在您的 .h 文件中:确保您符合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";
}
于 2013-08-23T16:00:02.083 回答
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
}

配置时不要忘记将委托设置为单元格。

于 2013-08-23T16:18:44.887 回答