MarkAurelius
MarkAurelius

Reputation: 1323

How to get the button that launched a segue in prepareForSegue?

I would like to use the title of the button that launches a segue as the title of the view that comes up. Is there a way to get that button in prepareForSegue? Otherwise, I have to have an otherwise unnecessary IBOutlet declared just for this one thing.

I'm using the latest XCode, 6 beta 7, and iOS 8 (and Swift, though this is all cocoa touch so answers in ObjC are fine).

Upvotes: 2

Views: 1299

Answers (2)

MarkAurelius
MarkAurelius

Reputation: 1323

sha's answer was right. Here is the code that I got working in Swift:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "MySegue" {
            if let myVC = segue.destinationViewController as? MyViewController {
                if let usender:AnyObject = sender {
                    if let button = usender as? UIButton {
                        myVC.title = button.titleForState(.Normal)
                    }

                }
            }
        }
    }

Then I noticed that the new signature has AnyObject!, so I changed it to this:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "MySegue" {
        if let myVC = segue.destinationViewController as? MyViewController {
            if let button = sender as? UIButton {
                    myVC.title = button.titleForState(.Normal)
            }

        }
    }
}

Upvotes: 0

sha
sha

Reputation: 17860

prepareForSegue has the following signature:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

sender will be your UIButton that user tapped.

Upvotes: 4

Related Questions