0

Right now I have 2 buttons that segue the textfield data from vc1 to vc2. I would like to have the top button segue whatever is in the textfield to vc2. I would like the bottom button to just segue to the next vc. Right now both buttons segue the data from the textfield to the next vc.

enter image description here

    import UIKit
class ViewController: UIViewController {
@IBOutlet var textfield: UITextField!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let c2 = segue.destination as? twoViewController else {return}
    c2.ss = textfield.text
}}

class twoViewController: UIViewController {
var ss: String!
@IBOutlet var datalbl: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    datalbl.text = ss
}}
  • Possible duplicate of [Passing Data between View Controllers](https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – Tamás Sengel Apr 17 '18 at 01:50
  • BTW, `class` names should start with a capital letter by convention in Swift: `TwoViewController`. Notice the syntax highlighting above didn't make your class name blue. – vacawama Apr 17 '18 at 02:32

1 Answers1

0

There are two ways you could handle this:

Use the sender and set the button's tag value

The sender in prepare(for:sender:) is the button that was pressed, so you can set unique tag values for your 2 buttons and then check that:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let c2 = segue.destination as? twoViewController else {return}
    if (sender as? UIButton)?.tag == 1 {
        c2.ss = textfield.text
    }
}

Set identifiers for the segues and check them in prepare(for:sender:)

Since you have two segues, click on the segue arrows in the Storyboard and set their identifiers in the Attributes Inspector. You could set the segue identifier for the top button to "sendTextField" and then check for that in prepare(for:sender:):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let c2 = segue.destination as? twoViewController else {return}
    if segue.identifier == "sendTextfield" {
        c2.ss = textfield.text
    }
}
vacawama
  • 150,663
  • 30
  • 266
  • 294