![](/img/trans.png)
[英]UITextField subview of UITableViewCell to become first responder?
[英]How to make a UITextField in a table cell become first responder?
如果我有一系列表格單元格,每個表格單元格都有一個文本字段,我將如何使特定的文本字段成為第一個響應者?
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UITextField *textField = [[UitextField alloc] init];
...
textField.delegate = self;
textField.tag = indexPath.row;
[cell addSubView:textField];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
我希望這可以幫助你......
Swift 4 :要使textfield成為tableview中的第一個響應者,只需將此擴展添加到tableView:
extension UITableView {
func becomeFirstResponderTextField() {
outer: for cell in visibleCells {
for view in cell.contentView.subviews {
if let textfield = view as? UITextField {
textfield.becomeFirstResponder()
break outer
}
}
}
}
}
然后在viewDidAppear()中調用becomeFirstResponderTextField():
func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.becomeFirstResponderTextField()
}
注意:我被認為是可以搜索的visibleCells
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.row==1)
{
[cell.txtField becomeFirstResponder];
}
return cell;
}
上面的代碼在第二個UItableView單元格中選擇(becomeFirstResponder)文本字段。謝謝
如果希望文本字段在加載表視圖后成為第一響應者,
NSIndexPath *indexPath = /* Index path of the cell containg the text field */;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// Assuming that you have set the text field's "tag" to 100
UITextField *textField = (UITextField *)[cell viewWithTag:100];
// Make it the first responder
[textField becomeFirstResponder];
UITextField繼承自UIResponder,后者實現了becomeFirstResponder消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.