textfielddidbegin editing not updating label - swift

My swift code below goal is when the user enters something into textfield tt it reflects it in currentPageLabel. The func that I thought would do this is having no effect. Nothing I enter into the textfield displays on the label. All of my code does not use a storyboard.
var currentPageLabel = UILabel()
var tt = UITextfield()
func textFieldDidBeginEditing(_ textField: UITextField) {
currentPageLabel.text = tt.text
}

Try this UITextFieldDelegate method:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
currentPageLabel.text = text
return true
}

You can use addTarget feature in this case! Just add target to your textField in viewDidload method, and add selector method marked with #objc textFieldDidChange. Inside textFieldDidChange function set text to your label!
textfield.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
#objc func textFieldDidChange(_ textField: UITextField) {
currentPageLabel.text = textField.text
}

Related

How do you set a maximum number value for a textfield in Swift that's flexible?

I would like to use the
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
}
I'm fetching a number from firebase which will be the maximum they will be allowed to type into a textfield. Fetching the number is easy, how do I set this maximum for the UITextField?
Just make a class and fill maximum number in storyboard as like:
import UIKit
#IBDesignable
class CustomTextField: UITextField {
#IBInspectable var maxLength: Int = Int.max {
didSet {
addTarget(self, action: #selector(limitLength), for: .editingChanged)
}
}
override func didMoveToWindow() {
super.didMoveToWindow()
addTarget(self, action: #selector(limitLength), for: .editingChanged)
}
#objc private func limitLength() {
guard let prospectiveText = text, prospectiveText.count > maxLength else {
return
}
let selection = selectedTextRange
text = String(prospectiveText.prefix(maxLength))
selectedTextRange = selection
}
}
you can use textField value;
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text.count <= maximumNumberOfCharachters {
...
}
return false
}

How to trigger code anytime a UItextfield is empty

I would like to have code for anytime a UItextfield is empty. Not just on the viewdidload but all the time. I tried putting something like if textField.isEmpty == true in the editing changed action although the issue I was having is if you type more than 5 characters and then hold down backspace the code doesn't get triggered. Any ideas for what to do?
Hi you need to subscribe on editing changed 
How to check if the field is empty?
let textField = UITextField()
textField.addTarget(self, action: #selector(textChanged), for: .editingChanged)
#objc func textChanged () {
if textField.text == "" || textField.text == nil {
print("IS EMPTY")
} else {
print("NON EMPTY")
}
}
How to set max length to UITextField
class ViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
let textField = UITextField()
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 5
}
}

Swift - How to limit the a few specific text field only allow to insert int?

How to limit the few specific text field only allow to insert int?
not all text fields. only a few specific ones.
Thank you.
Try this one.
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet var yourTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
yourTextField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For mobile numer validation
if textField == yourTextField {
//Add specific int numbers
let allowedCharacters = CharacterSet(charactersIn:"0123 ")//Here change this characters based on your requirement
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
}
Tried setting your textField's keyboard type?
yourTextField.keyboardType = .numberPad
Can also look into the delegate method
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
You can from there add logic to return true or false if the textField's selection meets your requirements

Where do I call my function so it successfully updates my UI?

I have written the following function to ensure my user fills in a textField before being able to continue.
func validateFields() -> String {
if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in textField"
}
return "A-OK."
}
func updateUI() {
let verdict = validateFields()
if verdict == "A-OK." {
self.buttonOne.alpha = 1
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
However, once the textField has been filled in, the above code fails to update the UI. I know I am missing out on something trivial here, I just cannot wrap my head around what. I'd really appreciate the help.
Use text textFieldDidEndEditing, textFieldDidBeginEditing, textFieldShouldReturn, etc. according to your requirement.
But I think delegate "textFieldShouldReturn" works fine with your requirement.
You just need to add you function updateUI() in this delegate.
That's easy you can create an outlet of your text fields and give its
delegate to self in viewDidLoad() method
#IBOutlet var txtfld: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
txtfld.delegate = self
}
// UITextField Delegates
func textFieldDidBeginEditing(_ textField: UITextField) {
print("TextField did begin editing method called")
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("TextField did end editing method called")
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("TextField should begin editing method called")
return true;
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
print("TextField should clear method called")
return true;
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
print("TextField should end editing method called")
return true;
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("While entering the characters this method gets called")
return true;
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("TextField should return method called")
textField.resignFirstResponder();
return true;
}
}
I suggest for calling your method you should use your updateUI()
function in textFieldShouldReturn(_ textField: UITextField) this
method.
I suppose you can easily bind you text view to a local property and observer changes on that property. And when everything is valid, you can enable your buttonOne and use the value of that property in future computations.
var myTextFieldData: String {
didSet {
updateUI()
}
}
Also, keep in mind that you'll also have to implement the UITextField delegate in order to bind your textField with myTextFieldData:
textField.delegate = self
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
myTextFieldData = string
return true
}

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