Reputation: 51
here is my exact setup of view controllers.The segue's kind is show.and the name is s1 here is my code:
import UIKit
class ViewController: UIViewController {
var x:String!
@IBOutlet weak var usr: UITextField!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "s1"){
let v = segue.destination as? ViewController222
v?.ab = usr.text!
}
}
@IBAction func b1(_ sender: UIButton) {
performSegue(withIdentifier: "s1", sender: nil)
}
}
And for the second view controller,ViewController222:
import UIKit
class ViewController222: UIViewController {
var ab:String!
@IBOutlet weak var l1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
l1.text=ab
}
}
can someone help? My program is crashing although the setup is correct
Upvotes: 0
Views: 77
Reputation: 423
You seem to have an awful lot of implicitly unwrapped optionals. Things like var ab:String! should be avoided. They just cause problems because they may be nil and you don't know it. Same with force unwrapping a variable. This is bound to cause an issue v?.ab = usr.text!. Best bet is to make use of if let and ?? to unwrap your optionals safely.
Try something like the following.
import UIKit
class ViewController: UIViewController {
var x: String?
@IBOutlet weak var usr: UITextField!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "s1"){
if let v = segue.destination as? ViewController222 {
v.ab = usr.text ?? ""
}
}
}
}
And second class
import UIKit
class ViewController222: UIViewController {
var ab: String?
@IBOutlet weak var l1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
l1.text = ab
}
}
And then in your storyboard make sure your segue is dragged from the button to ViewController222.
Upvotes: 0
Reputation: 77690
OK - I would suggest:
run your app and see if you no longer get the crash.
Note: do not re-assign the IBAction to the button.
Upvotes: 0
Reputation: 54785
You shouldn't manually call performSegue(withIdentifier:sender). When you add a segue in Interface Builder, an action is automatically added as well and it is called when you press the button to which the segue is attached. prepare(for segue) is called automatically by the system when you press the button.
Just delete your IBAction and it should work fine.
Upvotes: 1