skip to Main Content

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) {
        
    }

2

Answers


  1. 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)")
        }
        
    }
    
    Login or Signup to reply.
  2. You can capture input data in a UITextField using following method.

    extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // This method is called when the user taps the return key on the keyboard
        textField.resignFirstResponder() // Hide the keyboard
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        // Call at the end
        if let text = textField.text {
            // User input goes here.
            print("User input: (text)")
        }
    }
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search