当我再次点击它时,如何清除我的UITextField文本?

时间:2014-07-10 02:54:57

标签: ios uitextfield

我有一个名为UITextField的{​​{1}},并要求用户输入要添加到10的数字和一个计算它的numberToAdd。然后是UIButton显示总和。

假设我在UILabel中输入数字5并按下计算,UITextField将显示15。

当我再次点击UILabel而不必手动删除号码5时,如何编写清除UITextField的代码?

3 个答案:

答案 0 :(得分:2)

首先你应该有一个标志,表示数字是否计算,用户点击计算按钮后,你应该打开那个标志,然后当用户再次点击TextField时,你可以使用UITextFieldDelegate检测操作并清除textfield,如下面的答案:

- (void)textFieldDidBeginEditing:(UITextField *)textField { 
    if (isCalculated) {  
        textField.text = @""; 
        isCalculated = NO;  
    }  
}

答案 1 :(得分:2)

你可以使用UITapGestureRecognizer在TextField上获取明文。首先你应该使用BOOL标志来知道它是否计算过来让BOOL标志是isCal。

 UITapGestureRecognizer *clearTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clearTextField:)];

 [self.textView addGestureRecognizer:clearTapRecognizer];

并在clearTextField方法中编写belove代码。

- (void)clearTextField:(UITapGestureRecognizer *)gestureRecognizer
{
     if(isCal)
     {
        UITextView *_textView = (UITextView*) gestureRecognizer.view;
        _textView.text=@"";
        isCal=NO;
     }
}

答案 2 :(得分:0)

我可以在三个解决方案中考虑您的问题:

选项1
每次触摸时清除TextField

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    if (textField == self.numberToAdd) {
        self.numberToAdd1.text = @"";
    }
}

选项2
只有在您已经计算出数字时才清除TextField

@property (nonatomic) BOOL calculateDone;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.calculateDone = false;
}

- (IBAction)calculate:(id)sender {

    //sum label number and textField number
    int sum = [self.label.text intValue] + [self.numberToAdd.text intValue];
    //set label
    self.label.text = [NSString stringWithFormat:@"%d", sum];

    // sum done true
    self.calculateDone = true;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    if (textField == self.numberToAdd)
    {
        if (self.calculateDone)
        {
            self.numberToAdd.text = @"";
            self.calculateDone = false;
        }
    }
}

选项3
单击“计算”按钮

时清除TextField
- (IBAction)calculate:(id)sender {

    //sum label number and textField number
    int sum = [self.label.text intValue] + [self.numberToAdd.text intValue];
    //set label
    self.label.text = [NSString stringWithFormat:@"%d", sum];

    //reset textField
    self.numberToAdd.text = @"";

}

您还可以查看TextField中输入的文字,因为您只需要TextField中的数字,对吗?

@property (strong, nonatomic) NSString *urlRegEx;
@property (strong, nonatomic) NSPredicate *urlRegExTest;

//This Regex accepts negative and positive numbers
self.urlRegEx = @"((-)?[0-9]*)";
self.urlRegExTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", self.urlRegEx];


- (IBAction)calculate:(id)sender {

    // if text is a valid Number
    if ([self.urlRegExTest evaluateWithObject:self.numberToAdd.text]) {

        int sum = [self.label.text intValue] + [self.numberToAdd.text intValue];
        self.label.text = [NSString stringWithFormat:@"%d", sum];
    }

}

你可以download an example code here