Search code examples
iosswiftxcodesender

Downcasting Any? to UIBarButtonItem


override func prepare(for segue: UIStoryboardSegue, sender:
        Any?) {
    if segue.identifier == "detailSegue" {
        let indexPath = tableView.indexPathForSelectedRow!
        let card = cards[indexPath.row]
        let detailTableViewController = segue.destination as! DetailTableViewController
        detailTableViewController.card = card
        detailTableViewController.picture = card.image
    } else if segue.identifier == "addEditSegue" {
        let addEditTableViewController = segue.destination as! AddEditTableViewController
        let buttonPressed = sender as? UIBarButtonItem
        if buttonPressed == cardsAddButton {
            addEditTableViewController.isNewCard = true
        } else {
            addEditTableViewController.isNewCard = false
        }
    }
}

Hi, I am new to Swift. I need to perform the same segue by either tapping a UIBarButtonItem (cardsAddButton) or by tapping on cells of a UITableView. Using print statements I found that buttonPressed is nil when I tap cardsAddButton. Why? How should I check what was the sender?


Solution

  • You – the developer – should know who the sender of prepare(for is. There are only three possibilities:

    1. If the segue is connected to the table view cell in Interface Builder then the sender is the UITableViewCell.
    2. If the segue is connected to the view controller in Interface Builder then the sender is the UIViewController.
    3. If performSegue is called in code then the sender is whatever you passed in the sender parameter (including nil).

    Your code can work only if you call performSegue in the IBAction of the button and pass the button instance as sender

    @IBAction func addCard(_ sender : UIBarButtonItem)
    {
        self.performSegue(withIdentifier:"addEditSegue", sender: sender)
    }