在自定义单元格中点击UIButton后显示新的ViewController

时间:2014-09-03 00:52:01

标签: uiviewcontroller swift uibutton custom-cell xcode6-beta5

Heyhey!

我希望显示一个带有Action的ViewController(自定义单元格中的UIButton的tappedInside)。在这种情况下,我无法控制 - 从自定义单元格中的UIButton拖动到NavigationController(嵌入了ViewController)。

我怎样才能意识到" tappedInside"在tableview的一行中的按钮(在自定义单元格中)将显示一个新的ViewController?

谢谢!

2 个答案:

答案 0 :(得分:2)

使用Xcode 6 beta 7,您的UITableViewControllerUITableViewCell子类将如下所示:

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
    }

}

答案 1 :(得分:2)

单击带有委托的单元格时可以触发:

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

要打开新的viewcontroller,如果您使用故事板,可以尝试:

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

希望有帮助