Reputation: 63
I have two view controllers: ViewController1 and ViewController2. My objective is, when the segue is triggered if a certain condition in ViewController1 is met a textfield in viewController2 to be disabled.
I have setup shouldPerformSegueWithIdentifier
and prepareForSegue
and everything works fine, but when i put the condition it crash saying that it found an error unwrapping an optional- the textfield.
my ViewController1 is :
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject!) -> Bool {
if condition1=true{
return true
}
else{
return false
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier=="segue"){
let destVC:ViewController=segue.destinationViewController as! ViewController2
if n==1{
destVC.myTextField.enabled=false
}
}
}
Upvotes: 0
Views: 87
Reputation: 72440
In prepareForSegue
method myTextField
of ViewController2
is not initialized yet, so thats why you are getting an error unwrapping an optional textField
, To solve your crash create one Bool
instance inside your ViewController2
and pass its value in prepareForSegue
method.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier=="segue"){
let destVC:ViewController=segue.destinationViewController as! ViewController2
if n==1{
destVC.isEnabled=false
}
}
}
Create instance isEnabled
inside ViewController2
like this and used it in the viewDidLoad
of ViewController2
var isEnabled: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
self.myTextField.enabled = self.isEnabled
}
Upvotes: 2
Reputation: 6251
You can set condition at your destination view controller then you can do this
myTextField.userInteractionEnabled = false
Enable and disable userInteractionEnabled of your textfield.
Upvotes: 0
Reputation: 602
The views associated with the destination controller are not yet loaded/instantiated at that point.
Create an instance boolean flag on the destination VC and set that in the prepare segue function. Then in viewDidLoad or later in the destination VC check for that switch and disable the text field.
Upvotes: 0