gpt4 book ai didi

ios - 在ios中使用标签动态生成和访问UITextField

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:02:45 26 4
gpt4 key购买 nike

我有一个像这样动态生成 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;
}

现在我想在单击其中一个按钮时启用和访问每个文本字段。我正在使用 tag 来访问这些文本字段,如下所示:

- (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 并且启用第 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中使用标签动态生成和访问UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27420457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com