Ad

How To Pass Data From One UIView To Another UIView With Using Only One ViewController In Swift?

- 1 answer

I'm creating a simple login form where the username from textfield should show up in the other UIView when clicking the Login button.

How do I pass data from textfield of a UIViewA and display the value from textfield to a label in UIViewB?

There's only 1 ViewController where the UIViews will interchanged so there's no segue needed.

here is the button function from the login UIView:

class UIView1: UIView {
        @IBAction func buttontohome(_ sender: Any) {
            if (usernamebox.text == username || usernamebox.text == email) && passwordbox.text == password
            {
               // load UIView2 and send username string to UIView2 label
            }
            else {
                loadViewFromNib()
                loginfaillabel.text = "Login failed"
            }

        }
        }

Here's the second UIView where the username string should appear once the login is succeed:

 class UIView2: UIView {

       @IBOutlet var labelforpassedvalue: UILabel!

        var usernamelabel = String()

func viewDidLoad() {
        super.viewDidLoad()
             labelforpassedvalue.text = "Welcome Bob, " + usernamelabel

    }
}

Please help...

Ad

Answer

I agree with luk2302; this is flawed design and you may want to rethink the way you're going about this.

That said, if you have to go about it this way, one approach would be to declare an optional in your main ViewController like so:

var usernameLabelText: String?

and then update its value when the buttontohome action is called:

usernameLabelText = usernamebox.text

I'll leave it to you to figure out how to replace the old UIView with the new one.

Ad
source: stackoverflow.com
Ad