UITableViewCell 中的 UITextField:didSelectRowAtIndexPath 中的 becomeFirstResponder [英] UITextField inside UITableViewCell: becomeFirstResponder in didSelectRowAtIndexPath
问题描述
我目前正在努力让它发挥作用.任何帮助表示赞赏.
I am currently trying to get this working. Any help is appreciated.
我有一个自定义的 UITableViewCell
,里面有一个 UITextField
.当我选择表格单元格时,我想让 UITextField
成为第一个响应者.
但是 [textField becomeFirstResponder];
返回 false.
I have a custom UITableViewCell
that has a UITextField
inside. When I select the table cell, I would like to make the UITextField
first Responder.
However [textField becomeFirstResponder];
returns false.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
UITextField *textField;
for (UIView *view in [cell subviews]) {
if ([view isMemberOfClass:[UITextField class]]) {
textField = ((UITextField *)view);
}
}
[textField becomeFirstResponder];
}
根据要求,文本字段的初始化.这是在 UITableViewCell
子类中完成的:
As requested, the initialisation of the textfield. This is done in the UITableViewCell
subclass:
- (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Init Textfield
_textField = [[UITextField alloc] init];
_textField.backgroundColor = [UIColor clearColor];
_textField.delegate = self;
[self addSubview:_textField];
}
return self;
}
推荐答案
如果您有自定义单元格,那么您可以执行以下操作:
If you have a custom cell, then you can do something like this:
@implementation CustomCell
#pragma mark - UIResponder
- (BOOL)canBecomeFirstResponder
{
return YES;
}
- (BOOL)becomeFirstResponder
{
return [self.textField becomeFirstResponder];
}
@end
然后在表视图委托中:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if ([cell canBecomeFirstResponder]) {
[cell becomeFirstResponder];
}
}
这篇关于UITableViewCell 中的 UITextField:didSelectRowAtIndexPath 中的 becomeFirstResponder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!