以编程方式在UITableViewCell中的一个按钮中呈现视图控制器(Swift)

15

我正在尝试使用户在单击表视图中的单元格时进入新的视图控制器。 更具体地说,当用户单击人名时,应将其带到该用户的个人资料,其中用户名为表视图单元格,个人资料为新的视图控制器。 我认为实现此操作的方法是使用".presentViewController(vc,animated:true,completion:nil)",但是当我这样做时,它会显示“myCell没有名为.presentViewController的成员” “以下是问题的屏幕截图”

如果有人可以帮助我解决这个问题,我将不胜感激。

4个回答

21

presentViewController:animated:completionUIViewController 的实例方法,而不是 UIView 或其子类。您可以尝试以下操作:

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

然而,我建议您使用UIViewControllerpresentViewController:animated:completion:方法。可以在UIViewControllercell之间实现回调机制。

就像这样:获取UI table view cell内的按钮点击


12

班宁的回答是可行的,但语法已经过时。从Swift 4开始:

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

3

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)

1
如果您为tableView创建了一个单独的类,这是一种好的实践方法,那么您可以像这样做:

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

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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接