【问题标题】:Show new ViewController after tapping UIButton in a custom cell在自定义单元格中点击 UIButton 后显示新的 ViewController
【发布时间】:2014-10-27 09:07:12
【问题描述】:

嘿嘿!

我想展示一个带有 Action 的 ViewController(在自定义单元格中的 UIButton 的tappedInside)。在这种情况下,我不能只是从自定义单元格中的 UIButton 控制拖动到 NavigationController(ViewController 是嵌入的)。

我如何才能意识到在 tableview 的一行中的 Button(在自定义单元格中)上的“tappedInside”会显示一个新的 ViewController?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    使用 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
        }
    
    }
    

    【讨论】:

    • 感谢您的回答!我认为有必要在 "push:" cell.button.addTarget(self, action: Selector("push:"), forControlEvents: .TouchUpInside) 前面添加 Selector
    • 有了 Swift,你不再需要它了。
    【解决方案2】:

    您可以在您单击具有委托的单元格时触发:

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

    要打开一个新的视图控制器,如果你使用故事板,你可以试试这个:

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

    希望有所帮助

    【讨论】:

    • 我认为问题是关于触发自定义单元格内的按钮,而不是触发单元格本身...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    相关资源
    最近更新 更多