Search code examples
iosswiftuikituitextfield

Capturing user input data in a UITextField


I created 2 UITextFields for the user to enter data (Int) into. I then want to create a var from the user input data to use in some equations. How do I go about recording the data that the user inputed into the blocks?

My code currently looks like this.

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
              
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }

    @IBAction func sMinInput(_ sender: UITextField) {
        
    }
    
    @IBAction func sMaxInput(_ sender: UITextField) {
        
    }

Solution

  • This is working for me. The key is to set your IBAction using whichever "Sent Event" you'd like. I chose "Editing Changed". You can add as many UITextFields (or anything, really) you'd like. Good luck!

    enter image description here

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var textField: UITextField!
        var text: String?
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }
        
        @IBAction func textFieldAction(_ sender: Any) {
            text = textField.text
            printWithUnderscore()
        }
        
        private func printWithUnderscore() {
            guard let str = text else { return }
            print("_\(str)")
        }
        
    }