Clear UITextField Placeholder text on tap - iphone

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 field I've clicked "Clear when editing begins" however this does not immediately remove the text when I tap in the text box (it only disappears when you start typing).
Is there any way of removing the placeholder text immediately on tapping in the text box?

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";
}

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"];
}

You should also check if text filed is empty then you should put place holder again
- (void)textFieldDidBeginEditing:(UITextField *)textField {
textField.placeholder = nil;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if ([textField.text isEqualToString:#""] || [[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0))
{
[textField setText:#""];
textField.placeholder = #"Your Placeholdertext";
}
}

use this..
- (void)textFieldDidBeginEditing:(UITextField *)textField{
textField.placeholder=nil;
}
don't forget to add the delegate for the textfield to your file Owner.

If you have more than one TextField
1) Add String variable to your class
class YourViewController : UIViewController {
var placeHolder = ""
2) Add UITextFieldDelegate
extension YourViewController : UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
placeHolder = textField.placeholder ?? ""
textField.placeholder = ""
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.placeholder == ""{
textField.placeholder = placeHolder
}
}

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=#"";
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
textField.placeholder=nil;
}
textfield delegate make place holder value to nil

The #etayluz 's solution is better (my opinion), because you don't need to worry about assigning placeholder'a text again.
If you have custom textFields in different places of your app and want them to behave equally (as I need in my case) you can add this code to your custom TextField's class:
class CustomTextField: UITextField, UITextFieldDelegate {
private func setup() {
//do additional setup like attributedPlaceholder, inset, etc.
self.delegate = self
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
// MARK: UITextFieldDelegate methods
func textFieldDidBeginEditing(textField: UITextField) {
textField.setValue(UIColor.clearColor(), forKeyPath: "_placeholderLabel.textColor")
}
func textFieldDidEndEditing(textField: UITextField) {
textField.setValue(UIColor.lightGrayColor(), forKeyPath: "_placeholderLabel.textColor")
}
}
But if you need to have specific UITextFieldDelegate's methods for individual textField you DO need to implement this logic for it individually:
class LoginViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var emailTextField: CustomTextField!
#IBOutlet weak var passwordTextField: CustomTextField!
override func viewDidLoad() {
super.viewDidLoad()
textFields = [emailTextField, passwordTextField]
for textField in textFields {
textField.delegate = self
}
// MARK: UITextFieldDelegate methods
func textFieldDidBeginEditing(textField: UITextField) {
textField.setValue(UIColor.clearColor(), forKeyPath: "_placeholderLabel.textColor")
}
func textFieldDidEndEditing(textField: UITextField) {
textField.setValue(UIColor.lightGrayColor(), forKeyPath: "_placeholderLabel.textColor")
}
}

In case of SWIFT 3 or later
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.placeholder = nil
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.placeholder = "Text Placeholder"
}

On Button action Event put this Code:
txtName.placeholder = #"";

Related

Swift UI Delegate methods not being working

I am trying to have my inputs inside of my UITextField show up in the debugger console, when I am typing in the created TextField however the Delegate Methods don't seem to be responding. I am expecting to see my print statement that are seen below for my UIdelegate methods, like when I first started typing, while I type, and when I press the 'return key'. All delegate methods do not seem to be activated, and I am not sure how to make my Textfield link to the delegate method directly. In addition, I have another UITextField (Not shown here), would I have to 'addTarget' to differentiate between the two?
class ViewController: UIViewController, UITextFieldDelegate {
let createUserName: UITextField = {
var myTextField = UITextField ()
myTextField.translatesAutoresizingMaskIntoConstraints = false
myTextField.placeholder = "Username" //set placeholder text
myTextField.font = UIFont.systemFont(ofSize: 14) // set font size of text field
myTextField.layer.borderWidth = 1.0 //set width
myTextField.layer.borderColor = UIColor.red.cgColor//set background color to a ui color
myTextField.layer.backgroundColor = UIColor.white.cgColor
myTextField.layer.cornerRadius = myTextField.frame.height/2
myTextField.autocorrectionType = .no // disable autocorrect when typing for .no, enable with .yes
myTextField.isSecureTextEntry = false// masked text
myTextField.keyboardType = .default //keyboard style is set to default
myTextField.returnKeyType = .default //retuen key text changed to "Done" instead of return
myTextField.clearButtonMode = .whileEditing
myTextField.delegate = self as? UITextFieldDelegate
return myTextField
}()
override func viewDidLoad() {
super.viewDidLoad()
createUserName.delegate = self
view.addSubview(createUserName)
setupUserName()
}
//UITextField Delegate methods
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("textfield should begin editting")
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
print("text field edit")
}
//see string that is typed in debugger for use to validate password and crossreference username
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let textFieldString = textField.text, let swtRange = Range(range, in: textFieldString) {
let fullString = textFieldString.replacingCharacters(in: swtRange, with: string)
print("FullString: \(fullString)")
}
return true
}
//dismiss keyboard when return button is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
print("text field return")
return true
}
}
Your viewController should inherit from UITextFieldDelegate
class YourViewController : UIViewController, UITextFieldDelegate {
// your code
}
Also in your ViewDidLoad, move your createUsername.delegate = self to last line.
That string:
myTextField.delegate = self as? UITextFieldDelegate
tell us that your VC don't directly conform protocol UITextFieldDelegate...
If you conformed swift doesn't add as? cast ...

Clearing and restoring placeholder in UITextField

I have an addTarget set up on UITextField that clears the placeholder text when editingDidBegin. But I don't know how to restore the placeholder text if the user clicks on another UITextField, or the field is left empty.
This is located in viewDidLoad()
firstInitialTextField.addTarget(self, action: #selector(clearPlaceholderInTextField), for: UIControl.Event.editingDidBegin)
This function is located in the main body of the program.
#objc func clearPlaceholderInTextField() {
firstInitialTextField.placeholder = ""
}
I have several fields I would like to apply this same functionality to.
Create outlet collection for all the textfields like
#IBOutlet var textFs:[UITextField]!
with different tag for each , And array of placeHolders that you set in viewDidLoad
var placeholders = [String]()
Then set the vc as the delegate for all of them in viewDidLoad
textFs.forEach { $0.delegate = self }
Implement
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.placeholder = ""
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.placeholder = placeholders[textField.tag]
}

How to capture the text from a UITextField swift 2.0

I am trying to simply capture the string typed into a UITextField in a GameController class that supports a MainViewController. My code below doesn't capture it into the wordAttempt string. Maybe its something to do with the textfield delegate which I am not sure how to set... Any help very much appreciated!
Class MainViewController: UIViewController {
required init?(coder aDecoder: NSCoder) {
controller = GameController()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
let gameView = UIView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight))
self.view.addSubview(gameView)
controller.gameView = gameView
}
and then
class GameController: NSObject, UITextFieldDelegate {
var gameView: UIView!
var writeText: UITextField!
self.writeText = UITextField(frame: CGRectMake(100,100,200,50))
writeText.delegate = self
writeText.becomeFirstResponder()
gameView.addSubView(writeText)
textFieldShouldReturn(writeText)
textFieldDidEndEditing(writeText)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
writeText.resignFirstResponder()
textFieldDidEndEditing(writeText)
return true
}
func textFieldDidEndEditing(textField: UITextField) {
self.wordAttempt = writeText.text ?? ""
writeText.resignFirstResponder()
}
If you want get informed anytime user enter some characters to your UITextField you should subscribe to it changes.
// inside your GameController
self.writeText = UITextField(frame: CGRectMake(100,100,200,50))
writeText.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
writeText.becomeFirstResponder()
...
func textFieldDidChange(textField: UITextField) {
let inputText = textField.text ?? ""
}
And you will get text that user type in intpuText variable. Because of optional type you should unwrap it before use. And ?? "" means "if it nil put empty string to intputText, otherwise - text". This is why you see Optional("") when you output text.
If you need to know only when user stop typing consider textFieldDidEndEditing(_:) method of UITextFieldDelegate.
class GameController: NSObject, UITextFieldDeleage {
...
self.writeText = UITextField(frame: CGRectMake(100,100,200,50))
writeText.delegate = self
writeText.becomeFirstResponder()
...
func textFieldDidEndEditing(textField: UITextField) {
let inputText = textField.text ?? ""
}
You need to have it detect that the text has changed. You could do this say with a separate button press. Or you could use the textField delegate function textFieldDidEndEditing and textFieldDidBeginEditing to detect when the text has changed. Note that you would have to set the textfield's delegate.

How to add text to an active UITextField

I have a couple of UITextField's and one UIButton. If I tap on the UIButton, I want to place some static text in the active UITextField.
So something like:
#IBAction func buttonEen(sender: UIButton) {
'active textField'.text = "static text"
}
But how do I determine which UITextField is the active UITextField and how do I reach it?
To write text in last active UITextField you have to make your UIViewController a delegate of UITextField
ex:
class ViewController: UIViewController, UITextFieldDelegate
declare a activeField variable
ex:
var activeField: UITextField?
then implements textFieldDidBeginEditing
ex:
func textFieldDidBeginEditing(textField: UITextField)
{
activeField = textField
}
So your button function will be something like
#IBAction func buttonEen(sender: UIButton) {
if activeField
{
activeField.text = "static text"
}
}
First you need to create your textfield delegate (probably in 'ViewDidLoad()') :
activeTxtField.delegate = self
Then you need to implement the textField delegate function:
extension 'YourVC': UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == activeTxtField {
// Do whatever you want
// e.g set textField text to "static text"
}
}
}

iPhone how to get UITextField's text while typing?

I'm trying to show changes made to a UITextField on a separate UILabel. Is there a way to capture full text of the UITextField after each character the user types in? Currently I'm using this method, but it does not capture the last character that the user has entered.
I know that UITextView has "didChange" method, but I could not find that method for a UITextField.
//does not capture the last character
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[self updateTextLabelsWithText: textField.text];
return YES;
}
How can I take text out of UITextField after each character entered?
Thank you!
First add one UITextField and UILabel to storyboard / nib
Now assign IBOutlet for UILabel (Here I have used myLabel)
Assign UITextFieldDelegate to file owner, also implement the same delegate in .h file
Use these lines of code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self updateTextLabelsWithText: newString];
return YES;
}
-(void)updateTextLabelsWithText:(NSString *)string
{
[myLabel setText:string];
}
Simply handle the "Editing Changed" event
[textField addTarget:self
action:#selector(editingChanged:)
forControlEvents:UIControlEventEditingChanged];
and the selector:
-(void) editingChanged:(id)sender {
// your code
}
You can do this manually, or with the storyboard by CTRL-Dragging the "Editing changed" Sent event to your .h, creating the editingChanged method for you.
Swift with addTarget Swift 2.0+
titleTextField.addTarget(self, action: #selector(textFieldTyping), forControlEvents: .EditingChanged)
And implement selector
func textFieldTyping(textField:UITextField)
{
//Typing
}
In Swift 2.0+
class CheckInViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
yourTextField.delegate = self
}
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
var updatedTextString : NSString = textField.text as NSString
updatedTextString = updatedTextString.stringByReplacingCharactersInRange(range, withString: string)
self.methodYouWantToCallWithUpdatedString(updatedTextString)
return true
}
}
Hope it helps you swift pioneers
In Swift 3.0:
Some of these solutions were one character behind, or for earlier versions of Swift and Obj-C. Here is what I am using for Swift 3.0
In the class I declared a placeholder to store the text.
var tempName = ""
In ViewDidLoad I used:
nameField.addTarget(self, action: #selector(typingName), for: .editingChanged)
Then I made a function called:
func typingName(textField:UITextField){
if let typedText = textField.text {
tempName = typedText
print(tempName)
}
}
Swift 3.0+: This worked very nicely for me.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
self.yourLabel.text = "\(textField.text ?? "")\(string)"
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == yourTextFieldOutletName
{
if yourTextFieldOutletName.isEmpty == false
{
youtlabelname.text = yourTextFieldOutletName.text!
}
}
return true
}
func textViewDidEndEditing(_ textView: UITextView) {
if textField == yourTextFieldOutletName
{
if yourTextFieldOutletName.isEmpty == false
{
youtlabelname.text = yourTextFieldOutletName.text!
}
}
}