所以我在UITableView的单元格中有一系列文本字段,它们位于UIViewController(不是表视图控制器)中。我可以编辑文本字段,但是 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField等委托方法不会被调用。
视图控制器的代理集为:
@interface NRSignUpViewController : UIViewController<UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDelegate, UITableViewDataSource>
声明字段:
@property (nonatomic, strong) UITextField *firstName;
@property (nonatomic, strong) UITextField *lastName;
@property (nonatomic, strong) UITextField *email;
和委托在viewDidLoad中设置:
_firstName.delegate = self;
_lastName.delegate = self;
_email.delegate = self;
这是cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"Cell"];
cell.accessoryType = UITableViewCellAccessoryNone;
}
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, table.frame.size.width-20, 30)];
tf.textColor = [UIColor blackColor];
tf.returnKeyType = UIReturnKeyNext;
switch (indexPath.row) {
case 0:
tf.placeholder = @"First name";
tf.autocapitalizationType = UITextAutocapitalizationTypeWords;
_firstName = tf;
break;
case 1:
tf.placeholder = @"Last name";
tf.autocapitalizationType = UITextAutocapitalizationTypeWords;
_lastName = tf;
break;
case 2:
tf.placeholder = @"Email address";
tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
tf.keyboardType = UIKeyboardTypeEmailAddress;
_email = tf;
break;
default:
break;
}
[cell.contentView addSubview:tf];
return cell;
}
任何可能缺少的想法?
答案 0 :(得分:3)
您要在viewDidLoad
中设置代理,但在cellForRow...
之前不会实际创建文本字段。
答案 1 :(得分:3)
在viewDidLoad
方法中添加断点,并检查文本字段是否为nil
。那是因为该对象尚未初始化。您应该在tableView:cellForRowAtIndexPath:
方法中设置委托,因为此时它们实际上已分配。
答案 2 :(得分:1)
我想你可以试试这个:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(methodNothing)
name:UITextFieldTextDidChangeNotification
object:firstName];
您可以使用:UITextFieldTextDidBeginEditingNotification
或UITextFieldTextDidEndEditingNotification