Clear UITextField Placeholder text on tap

后端 未结 10 1605
情书的邮戳
情书的邮戳 2021-01-31 04:33

In Xcode4 I\'ve created some placeholder text for a UITextField and I\'d like it to clear when the user taps in the box.

So, in the Attributes Inspector for the text fie

相关标签:
10条回答
  • 2021-01-31 05:10

    make your ViewController the delegate of the textField and implement those two methods:

    - (void)textFieldDidBeginEditing:(UITextField *)textField {
        textField.placeholder = nil;
    }
    
    - (void)textFieldDidEndEditing:(UITextField *)textField {
        textField.placeholder = @"Your Placeholdertext";
    }
    
    0 讨论(0)
  • 2021-01-31 05:12
    - (void)textFieldDidBeginEditing:(UITextField *)textField{
        textField.placeholder=nil;
    }
    

    textfield delegate make place holder value to nil

    0 讨论(0)
  • 2021-01-31 05:18

    The solution provided by Matthias Bauch works well, but what happens when you have more than one UITextField to worry about? Now you have to identify which UITextField is referred to in textFieldDidEndEditing:textField (possibly by use of the tag property), and that results in more unnecessary code and logic.

    A much simpler solution: simply assign a clear color to the placeholder text , and when done editing, revert back to it's original color. This way, your textFieldDidEndEditing:textField doesn't have to identify the textField to set back its corresponding text after it was nullified as in Bauch's solution.

    - (void)textFieldDidBeginEditing:(UITextField *)textField {
        [textField setValue:[UIColor clearColor] forKeyPath:@"_placeholderLabel.textColor"];
    }
    
    - (void)textFieldDidEndEditing:(UITextField *)textField {
        [textField setValue:[UIColor placeholderColor] forKeyPath:@"_placeholderLabel.textColor"];
    }
    
    0 讨论(0)
  • 2021-01-31 05:19

    On Button action Event put this Code:

    txtName.placeholder = @"";
    
    0 讨论(0)
  • 2021-01-31 05:21

    In your .h file declare a function like

    -(IBAction)clear:(id)sender;

    attach this function to your touchdown event of your UITextField.

    in your .m file

     -(IBAction)clear:(id)sender 
    
    {
       myplaceHolderText.text=@"";
     }
    
    0 讨论(0)
  • 2021-01-31 05:25

    In case of SWIFT 3 or later

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.placeholder = nil
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        textField.placeholder = "Text Placeholder"
    }
    
    0 讨论(0)
提交回复
热议问题