Leaf Leaf - 1 year ago 40
iOS Question

Segue performing prematurely in if / else clause

The following code

class ViewController: UIViewController {

@IBOutlet weak var knock: UIButton!
@IBOutlet weak var label: UILabel!

var count: Int = 0
var unlocked: Int = 0

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.


override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

@IBAction func knockKnock(sender: UIButton) {

if count < 20 {
label.text = "Knocked \(count) times."

} else if count > 19 && count < 40 {
label.text = "Knocked \(count) times."
label.textColor = UIColor.randomColor()

} else if count > 39 && count < 100 {
label.text = "That's enough."
label.textColor = UIColor.blackColor()

} else if count > 99 && count < 102 {
label.text = "I wish you hadn't done that."
label.textColor = UIColor.redColor()

} else if count == 103 {
label.text = "Fine, come in."
label.textColor = UIColor.greenColor()
count = 126
unlocked += 1


if unlocked > 0 {
self.performSegueWithIdentifier("InsideHomeSegue", sender:sender)

count += 1


is prematurely performing the Segue in

if unlocked > 0 {
self.performSegueWithIdentifier("InsideHomeSegue", sender:sender)

The segue is performed immediately the first time the button is pressed, which I do not understand, as at that point the code should be unreachable behind a false
statement, since int
is initialized with

I have had similar problems which turned out to be issues with XCode itself rather than my code; I have looked through all the files I can find referencing any variables or objects in Interface Builder, checked for naming inconsistencies, rogue outlets, etc.

I still have a very shaky understanding of Segues, and would appreciate any detailed help anyone can offer.

The larger
else if
block worked properly all the way up to the final increment until Segue code was added.
Originally the
self.performSegueWithIdentifier("InsideHomeSegue", sender:sender)
line was inside the
else if count == 103 {
var unlocked: Int
was added to combat the Segue issue to no avail.

I've read through several pages of the XCode documentation on Segues, but haven't found anything else I can try.

It's possible I've overlooked something incredibly obvious, but regardless, thanks for reading.


EDIT: I have checked all outlets, it's the only Segue in the project currently and it isn't hooked up anywhere else. The Segue is activated on a button press, not immediately on View load.

Answer Source

Just like what my comment said, You've connected the segue with your button, so that the segue will alway execute. It has nothing to do with if clause.

You should connect with the ViewController instead of connecting with a button