以编程方式创建UITextFields

时间:2012-02-03 15:25:14

标签: objective-c ios uitextfield

我无法弄清楚这里有什么问题。请参阅NSLog功能上面的内容。

-(void)loadView
{
    ......    
    int x_position = 10;
    for (self.x = 0; self.x < 3; self.x++) 
    {
        self.textField = [[UITextField alloc] initWithFrame:CGRectMake(10, x_position, 300, 25)];
        self.textField.tag = self.x;
        // Output 0, 1, 2
        NSLog(@"%d", self.x);
        x_position += 40;

       [self.view addSubview:self.textField];
    }


    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn addTarget:self action:@selector(showNames) forControlEvents:UIControlEventTouchDown];
    [btn setTitle:@"Remove from view" forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, x_position + 30, 210, 50);

    [self.view addSubview:btn];
    [self.textField release];
    [self.view release];
}

-(void)showNames
{
    while (self.x > 0) {
        self.x--;
        // output 2, 1, 0
        NSLog(@"%d", self.x);
        NSLog(@"%@", tmp);
    }
}

这是控制台日志

<UITextField: 0x4b39410; frame = (10 90; 300 25); text = 'Ad'; clipsToBounds = YES; opaque = NO; tag = 2; layer = <CALayer: 0x4b38c30>>
<UITextField: 0x4e22320; frame = (10 50; 300 25); text = 'Asd'; clipsToBounds = YES; opaque = NO; tag = 1; layer = <CALayer: 0x4e0a4c0>>
<UIView: 0x4b32330; frame = (0 20; 320 460); layer = <CALayer: 0x4b329a0>>

我希望标签0的对象是UITextField,而不是UIView。 这有什么不对?

1 个答案:

答案 0 :(得分:3)

每个视图的标签默认为零,因此您的主UIView标签为零,因此您未明确设置标签的任何其他视图也是如此。

我建议您为代码使用偏移值,这样您就可以使它们都是唯一的。例如:

#define TEXTFIELD_TAG_OFFSET 100

for (self.x = 0; self.x < 3; self.x++) 
{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(10, x_position, 300, 25)];
    self.textField.tag = self.x + TEXTFIELD_TAG_OFFSET;
    // Output 0, 1, 2
    NSLog(@"%d", self.x);
    x_position += 40;

   [self.view addSubview:self.textField];
}

现在您可以使用标签编号TEXTFIELD_TAG_OFFSET + N来引用第N个文本字段。这样,您的文本字段都将具有唯一标记。