objective-c - 以编程方式创建 UITextFields

标签 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。
这里有什么问题?

最佳答案

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

我建议为您的标签使用偏移值,这样您就可以使它们都独一无二。例如:

#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 个文本字段。这样您的文本字段都将具有唯一的标签。

关于objective-c - 以编程方式创建 UITextFields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9131062/

相关文章:

iphone - Cocos2d : Initializing layers by node - class is nil

ios - 导航 UI 未使用 Xcode 9 更新

ios - 如何给 UITextfield 的左上角和右上角边框

ios - 无法在 Storyboard上的 SWRevealViewController 中设置委托(delegate)

objective-c - #if DEBUG 在 TestFlight 版本的某些设备上不起作用

objective-c - UIToolbar 在状态栏下滑动

iphone - 取消隐藏 View 时,becomeFirstResponder 会减慢应用程序的速度

ios - 如何在 iOS 中的线程之间传递 RLMObject?

iphone - 如何使 UIWebView 平滑滚动?

ios - 更改安全 UITextField 的行为