简体   繁体   中英

How do I use UI button to call a new controller in swift?

I've got an instance of a button and I also have two textfields for usernames and passwords. it is a test app therefor I have hard coded usernames and password and passed strings into it as such

@IBOutlet weak var usernameTextfield: UITextField!

@IBOutlet weak var passwordTextfield: UITextField!

let username = "itishim"
let password = "password"

I just created a new view controller (viewcontroller2), drag it to story board and controlled dragged the main view controller to the new view controller. My goal is to use the button to segue to the new view controller if the password I hardcoded is true.

    @IBAction func button(sender: AnyObject) {


    if usernameTextfield.text == username && passwordTextfield.text == password {


    self.performSegueWithIdentifier("nextView", sender: self)
    } else {
            print("nope")

I keep getting "[UIViewController button:]: unrecognized selector sent to instance 0x7f8731515400" even though I have the right username and password. I am new to swift and would appreciate any help I get. Thanks!

I checked your zip file. It crashes even though there is no segue. I propose you built a new project. And do the following.

  1. Drag a viewController and set it with a new SecondViewController.swift
  2. Go to storyBoard and from the firstViewController make a segue to the secondviewController by draging from the first (yellow ) button at the top the secondViewCOntroller and click show.
  3. Add your textFields and button
  4. Add button action in viewCOntroller.
  5. Click the segue in storyboard and give it name "nextView"

And then it the button function

 @IBAction func ButtonFuntion(_ sender: AnyObject) {
        if usernameTextfield.text == username && passwordTextField.text == password{
            performSegue(withIdentifier: "nextView", sender: nil)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM