Clear UITextField Placeholder text on tap

后端 未结 10 1786
情书的邮戳
情书的邮戳 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: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"];
    }
    

提交回复
热议问题