【问题标题】:Don't recreate UITextField on Tap if UITextField is already created如果 UITextField 已经创建,不要在 Tap 上重新创建 UITextField
【发布时间】:2014-08-08 09:58:17
【问题描述】:

我有一些想法,但是对于第一次创建带有“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.");
    }
}

【问题讨论】:

    标签: ios objective-c uitextfield uitapgesturerecognizer


    【解决方案1】:

    当然。创建 UITextField 时,您可以分配一个标签:

    textField.tag = 1001;
    

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

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

    【讨论】:

      【解决方案2】:

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

      @property (strong, nonatomic) UITextField *textField;
      

      然后在您的点击功能中测试 self.textField 是否为空:

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

      记得将代码中的所有textfield 替换为self.textfield

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-19
        • 2010-11-23
        • 2011-06-03
        • 2013-01-12
        • 2012-02-02
        • 2012-12-14
        相关资源
        最近更新 更多