Mohammed Riyadh
Mohammed Riyadh

Reputation: 1019

How to move to other viewControllers when user tap on a tableView cell

I have a navigation bar with a table view controller that display 4 images (4 cells). I have 4 viewControllers that I need to show when the user clicks on the cell ( each image show a specific VC ) ??

any ideas would be much appreciated

here is my code :

class MenuTable: UITableViewController {

    @IBOutlet weak var imgtable: UITableView!

    var menuImage: [UIImage] = [
        UIImage(named: "image1")!,
        UIImage(named: "image2")!,
        UIImage(named: "image3")!,
        UIImage(named: "image4")!
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        imgtable.dataSource = self
        imgtable.delegate = self
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuImage.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("menucell") as! Menucell
        cell!.imageview.image = menuImage[indexPath.row]

        return cell
    }

}

Upvotes: 2

Views: 2434

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You need to implement didSelectRowAtIndexPath delegate method of UITableView like this

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var viewController: UIViewController = UIViewController()
    switch (indexPath.row) {
        case 0:
            viewController = self.storyboard?.instantiateViewControllerWithIdentifier("viewController1") as! viewController1
        case 1:
            viewController = self.storyboard?.instantiateViewControllerWithIdentifier("viewController2") as! viewController2
        case 2:
            viewController = self.storyboard?.instantiateViewControllerWithIdentifier("viewController3") as! viewController3
        case 3:
            viewController = self.storyboard?.instantiateViewControllerWithIdentifier("viewController4") as! viewController4
        default:
            print("default")
    }
    self.navigationController?.pushViewController(viewController, animated: true)
}

Upvotes: 1

Related Questions