[英]Telling a UITextField to become first responder while embedded in a UITableViewCell
I have a UITextField
that is a subview of a UITableViewCell
.我有一个
UITextField
是UITableViewCell
的子视图。
When my view loads, I want the text field to become first responder.当我的视图加载时,我希望文本字段成为第一响应者。 I have a pointer to the text field in the table cell, so to do this I am trying:
我有一个指向表格单元格中文本字段的指针,因此我正在尝试执行此操作:
[myTextField becomeFirstResponder];
This returns NO
all the time, regardless of when it's called, which according to the docs means the text field refused to become first responder... What am I doing wrong?无论何时调用,这始终返回
NO
,根据文档,这意味着文本字段拒绝成为第一响应者......我做错了什么?
Edit:编辑:
The textfield
properly responds to being touched. textfield
正确响应被触摸。 It bring up the keyboard then.然后它会调出键盘。 It's only when telling it to
becomefirstresponder
programmatically that the problem happens.只有当它以编程方式告诉它成为
becomefirstresponder
,问题becomefirstresponder
发生。
It turned out that the text field was nil when I was trying to send it first responder.事实证明,当我尝试发送第一响应者时,文本字段为零。 Sending
becomeFirstResponder
later in the life cycle worked.在生命周期的后期发送
becomeFirstResponder
有效。
I was having the same problem with a textfield I had added as a subview to a grouped table view cell - but figured out a solution after some poking around.我在作为子视图添加到分组表视图单元格的文本字段中遇到了同样的问题 - 但经过一番探索后找到了解决方案。
Assuming you have given the textfield a tag in your cellForRowAtIndexPath method, you can do something like this:假设您在 cellForRowAtIndexPath 方法中为文本字段指定了一个标签,您可以执行以下操作:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
myTextField = (UITextField *)[cell viewWithTag:kMyTextFieldTag];
[myTextField becomeFirstResponder];
}
Calling it in the -(void)viewDidLoad would work.在 -(void)viewDidLoad 中调用它会起作用。
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.myTextField becomeFirstResponder]
//... any other code you need
}
I was not getting the cursor to show up when the UITextField
was made first responder inside of the cellForRowAtIndexPath
.当
UITextField
成为cellForRowAtIndexPath
内的第一响应者时,我没有让光标显示。 The text field would work just fine and dandy, but it was not showing the blinking cursor inside of the field.文本字段可以正常工作,但它没有在字段内显示闪烁的光标。 When you would press and hold, the zoom magnify would also not show a cursor.
当您按住时,缩放放大也不会显示光标。
I got around this odd issue by setting my becomeFirstResponder
inside of the didSelectRowAtIndex
method.我通过在
didSelectRowAtIndex
方法中设置我的becomeFirstResponder
解决这个奇怪的问题。
您的 UITableView editing
属性是否设置为YES
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.