Clement Bisaillon
Clement Bisaillon

Reputation: 5177

How to change view when tapping button in a custom UITableViewCell

Usually, I change view like this:

var goBackToMainView:MainViewController = self.storyboard?.instantiateViewControllerWithIdentifier("navigation2") as MainViewController

self.presentViewController(goBackToMainView, animated: true, completion: nil)

But if I try to do this in my custom UITableViewCell when the user tap a button, it gives me errors like customTableViewCell does not have a member named 'storyboard' and 'presentViewController'

How can I change views in my TableViewCell ?

Upvotes: 0

Views: 126

Answers (2)

Jaune Sarmiento
Jaune Sarmiento

Reputation: 134

Why do it in the UITableViewCell subclass? You should be doing your view management in the ViewController.

In your view controller:

import UIKit

// Take note of UITableViewDelegate, you'll need it to be able to use
// tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
class MyTableViewController: UITableViewController, UITableViewDelegate {

    // Assuming that you have a storyboard variable in AppDelegate
    let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate

    // .. more code here like viewDidLoad, etc.

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var viewController = appDelegate.storyboard.instantiateViewControllerWithIdentifier("MainViewController") as MainViewController

        // This will probably appear as a modal
        self.presentViewController(viewController, animated: true, completion: nil)
    }

}

Note: I just did a quick playground for the code above so you may need to unwrap optionals.

If you have your view controller embedded in a navigation controller, you might want to use Unwind Segues. More information about that here: What are Unwind segues for and how do you use them?

Cheers!

Upvotes: 1

Leandroc
Leandroc

Reputation: 75

Have you tried adding as a subview?

Example:

var tableViewCell = UITableViewCell(frame: aFrame)

tableViewCell.addSubview(aView)

Upvotes: 1

Related Questions