2

Heyhey!

I'd like to show a ViewController with an Action (tappedInside of a UIButton in a custom cell). In this case I can't just control-drag from the UIButton in the custom cell to the NavigationController (ViewController is embedded).

How can I realize that a "tappedInside" on a Button (in a custom cell) in a row of a tableview will show up a new ViewController?

Thank you!

Joe
  • 207
  • 1
  • 2
  • 9

2 Answers2

2

With Xcode 6 beta 7, your UITableViewController and UITableViewCell subclasses would look like this:

import UIKit

class CustomCell: UITableViewCell {

    @IBOutlet weak var button: UIButton!

}

class TableViewController: UITableViewController {

    //Set method for UIButton
    func push(sender: AnyObject) {
        navigationController!.pushViewController(storyboard!.instantiateViewControllerWithIdentifier("ViewController") as ViewController, animated: true) //where ViewController is the name of the UIViewController and "ViewController" the identifier you set for it in your Storyboard
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomCell
        cell.selectionStyle = .None

        //Set button's target
        cell.button.addTarget(self, action: "push:", forControlEvents: .TouchUpInside)

        return cell
    }

}
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218
  • Thanks for your answer! I think it's necessary to add Selector in front of "push:" cell.button.addTarget(self, action: Selector("push:"), forControlEvents: .TouchUpInside) – Joe Sep 07 '14 at 23:13
  • With Swift, you don't need that anymore. – Imanou Petit Sep 08 '14 at 13:04
2

You can trigger when you click a cell with the delegate:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
  // some code
}

To open a new viewcontroller, if you use a storyboard you can try this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newVC = storyboard.instantiateViewControllerWithIdentifier("myIdentifier") as youClassController
self.presentViewController(newVC, animated: false, completion: nil)

Hope that help

Mk3d
  • 96
  • 5