Clearing and restoring placeholder in UITextField - swift

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

Related

textfield to a label atumatically?

Is there any way in which I can send information from a textfield to a label automatically while writing for example if I have 2 texfield and 1 label
one by name and the other by last name
that when writing a single letter or a name this automatically appears in the label
some way to do this with de button
-> #IBAction func bt(_ sender: Any) { text =texfield!.text text = txfield!.text text.text = "\(textt!) \(texxt!)"
You can add this text change listener in your viewDidLoad method of View Controller.
yourTextField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)
And add this function to your View Controller
#objc func textFieldDidChange(_ textField: UITextField) {
yourLabel.text = textField.text
}

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 ...

textfield not empty show save button in Swift

My save button is hidden with the function saveBtnHidden() in the code below. However, the save button won't reappear when text is typed into the text field. I have tried multiple solutions similar to this. Every time that I type into the text field, the save button just won't show up.
import UIKit
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var nicknameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
saveBtnHidden()
}
func saveBtnHidden() {
if (nicknameField.text?.isEmpty ?? true) {
// is empty
saveBtn.isHidden = true
} else {
saveBtn.isHidden = false
}
}
#IBAction func saveBtnPressed(_ sender: Any) {
performSegue(withIdentifier: "nextPage", sender: nil)
}
}
You are getting this error because your function saveBtnHidden() is only called once in viewDidLoad(). It does not get called again when the text in your text field changes. To detect when text changes, you will need to add a target to your text field that calls a function when it changes (.editingChanged) like this:
nicknameField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
Then in the textFieldDidChange call your saveBtnHidden() function:
func textFieldDidChange(_ textField: UITextField) {
saveBtnHidden()
}
Code adapted from: How do I check when a UITextField changes?
Use delegate to be notify of any change. Delegates is a key part of iOS development and Apple's framework.
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var nicknameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
saveBtnHidden()
nicknameField.delegate = self
}
func textFieldDidChange(_ textField: UITextField) {
saveBtnHidden()
}
// More of your source code below...

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