开发者社区> 问答> 正文

动态创建一堆UITextField,怎么准确获取某一个

这样根据数据信息,动态创建了一堆UITextField,每一个UITextField都对应了一个UIButton。

for(i=0; i<[users count]; i++)
{
    NSString *name = [users objectAtIndex:i];
    UITextField *user = [[UITextField alloc] initWithFrame:CGRectMake(0.f, top, 200.f, 30.f)];
    user.text = name;
    user.returnKeyType = UIReturnKeyDone;
    user.keyboardType = UIKeyboardTypeDefault;

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(220.f, top, 80.f, 30.f)];
    [btn addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];

    [self.scroller addSubview:user];
    [self.scroller addSubview:btn];

    top = top + 40;
}

现在要通过点击某个Button,修改对应的UITextField的值
之前都是把UITextField做成全局变量的,现在动态创建不能全局了,怎么办?

展开
收起
a123456678 2016-07-19 15:11:37 1682 0
1 条回答
写回答
取消 提交回答
  • 创建时

    for(i=0; i<[users count]; i++)
    {
        NSString *name = [users objectAtIndex:i];
        UITextField *user = [[UITextField alloc] initWithFrame:CGRectMake(0.f, top, 200.f, 30.f)];
    
        //注意这句
        user.tag = i;
        //注意上面这句
        user.text = name;
        user.returnKeyType = UIReturnKeyDone;
        user.keyboardType = UIKeyboardTypeDefault;
    
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(220.f, top, 80.f, 30.f)];
        [btn addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
    
        [self.scroller addSubview:user];
        [self.scroller addSubview:btn];
    
        top = top + 40;
    }
    获取时

    UITextField *user = [self.scroller viewWithTag:i];
    另建议将user命名为userTextField

    2019-07-17 19:58:25
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载