如果已创建UITextField,则不要在Tap上重新创建UITextField

时间:2014-08-08 09:58:17

标签: ios objective-c uitextfield uitapgesturerecognizer

我有一些想法,但当然对于第一次使用" if条件"创建UITextField并不行。 我该怎么做? 如果UITextField已经存在"我可以创建类似"的条件吗? ???

这是我的代码:

-(void)tapDetected:(UIGestureRecognizer*)recognizer{
    NSLog(@"tap detected.");
    CGPoint point = [recognizer locationInView:self.truckImageView];
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, point.y, 300, 40)];
    [textField becomeFirstResponder];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.font = [UIFont systemFontOfSize:24];
    textField.placeholder = @"enter text";
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.keyboardType = UIKeyboardTypeDefault;
    textField.returnKeyType = UIReturnKeyDone;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    textField.delegate = self;
    if (textField.text && textField.text.length > 0)
    {
    [self.view addSubview:textField];
    //    textField.alpha = 0.5;
    [textField setBackgroundColor:[UIColor clearColor]];
    }
    else
    {
        NSLog(@"textField is already created.");
    }
}

2 个答案:

答案 0 :(得分:1)

不确定。创建UITextField时,您可以指定一个标记:

textField.tag = 1001;

然后在再次创建之前,您可以检查

UITextField *txt = [self.view viewWithTag:1001];
if(txt.tag == 1001)
  return;

答案 1 :(得分:-1)

我会在头文件中声明一个UITextField,如下所示

@property (strong, nonatomic) UITextField *textField;

然后在tap函数中测试self.textField为null:

if(self.texField == NULL){
    //enter code
}

请记住在代码中将所有textfield替换为self.textfield