我有一个动态生成 UITextField 的代码,如下所示:
UITextField *myTextfield;
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView* headerView = [[UIView alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 640.0f, 0.0f)];
//for (int i=0; i<4; i++) {
myTextfield = [[UITextField alloc] initWithFrame:CGRectMake(20, 60*i+20, 280, 45)];
myTextfield.text = [NSString stringWithFormat:@"Value: %d", section];
myTextfield.enabled = NO;
myTextField.tag = section;
[headerView addSubview:myTextField];
}
我还在每个文本字段旁边生成了一个编辑按钮。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CustomCellIdentifier = @"cell1";
cell = (ButtonCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ButtonCell"
owner:self options:nil];
for (id oneObject in nib) if ([oneObject isKindOfClass:[ButtonCell class]])
cell = (ButtonCell *)oneObject;
}
cell.msg_btn.tag = indexPath.section;
cell.changecolor_btn.tag = indexPath.section;
cell.picklist_btn.tag = indexPath.section;
cell.adddelsubmenu_btn.tag = indexPath.section;
cell.done_btn.tag = indexPath.section;
[cell.msg_btn addTarget:self action:@selector(editEachTextField:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
现在,我想在单击其中一个按钮时启用并访问每个文本字段。我使用标签来访问这些文本字段,如下所示:
- (void) editEachTextField:(UIButton*)sender
{
myTextfield = (UITextField *)[self.view viewWithTag:myTextfield.tag];
myTextfield.enabled = YES;
[myTextfield becomeFirstResponder];
NSLog(@"Tag value of Textfield: %ld",(long)myTextfield.tag);
NSString *text = [(UITextField *)[self.view viewWithTag:myTextfield.tag] text];
NSLog(@"Value: %@", text);
}
但是每当我单击其中一个按钮时,它都会返回标记值=4,并且第四个文本字段将启用编辑。有什么问题吗?
最佳答案
您正在使用 myTextfield.tag
值来启用文本字段,而不是单击按钮的标记。
myTextfield
指向最后分配的 UITextField
(其中具有标签 4),这就是为什么您获得的标签值为 4 并且最后一个文本字段被启用。
问题出在这段代码上:
myTextfield = (UITextField *)[self.view viewWithTag:myTextfield.tag];
将其更改为:
myTextfield = (UITextField *)[self.view viewWithTag:sender.tag];
注意:
如果按钮和文本字段放置在同一 View 中,请勿对它们使用相同的标记。如果这样做,您将无法确定使用 viewWithTag
时将获得哪个对象。
关于ios - ios中使用tag动态生成并访问UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27420457/