以编程方式在UITableViewCell中显示带有按钮的视图控制器(Swift)

时间:2015-06-09 15:25:56

标签: ios swift uitableview uiviewcontroller presentviewcontroller

我试图在用户点击表格视图中的表格视图单元格时将其带到新的视图控制器。更具体地说,当用户点击人员用户名时,它应该将他们带到该用户档案。用户名是表视图单元格,配置文件是新视图控制器。我认为这样做的方法是使用“.presentViewController(vc,animated:true,completion:nil)”然而,当我这样做时,它说“myCell没有名为.presentViewController的成员”Below is a screenshot of the issue

如果有人能帮我解决这个问题,我们将不胜感激

4 个答案:

答案 0 :(得分:18)

presentViewController:animated:completionUIViewController而不是UIView或其子类的实例方法。你可以试试这个:

self.window?.rootViewController.presentViewController(specificViewController, animated: true, completion: nil)

但是,我建议您使用presentViewController:animated:completion:中的UIViewController方法。可以在UIViewControllercell之间实现回调机制。

像这样:Get button click inside UI table view cell

答案 1 :(得分:6)

Banning的答案有效,但语法很老。来自 Swift 4

self.window?.rootViewController?.present(vc, animated: true, completion: nil)

答案 2 :(得分:2)

swift3

let storyboard = UIStoryboard(name: "MainViewController", bundle: nil)
let messagesViewController = storyboard.instantiateViewController(withIdentifier: "MessagesViewController") as! MessagesViewController
self.window?.rootViewController?.present(messagesViewController, animated: true, completion: nil)

答案 3 :(得分:0)

如果你为tableView创建了一个单独的类,那么这是一个很好的做法,你可以这样做:

首先,创建 addTarget 创建单元格(cellForRowAt):

cell.dropdownBtn.addTarget(self, action: #selector(self.openListPickerVC(_:)), for: .touchUpInside)

之后,在openListPickerVC()中显示视图控制器:

@objc func openListPickerVC(_ sender: UIButton) {
    let index = sender.tag
    let vc: PickerViewController = UIStoryboard(name: "Main", bundle: 
             Bundle.main).instantiateViewController(withIdentifier: 
             "PickerViewController") as! PickerViewController

     self.present(vc, animated: true, completion: nil)
}