Presenting a View Controller with a button in a UITableViewCell programmatically (Swift)

南楼画角 提交于 2019-12-05 00:26:27
Bannings

The presentViewController:animated:completion is an instance method of the UIViewController not UIView or a subclass of. You can try this:

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

However, I suggest that you should use the presentViewController:animated:completion: method from UIViewController. A callback mechanism can be achieved between the UIViewController and the cell.

Like so:Get button click inside UI table view cell

The Doctor

Banning's answer works, however the syntax is old. From Swift 4:

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

swift3 version

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

If you have created a separate class for tableView which is a good practice then, you can do it like this:

First, create addTarget where the cell is created (cellForRowAt):

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

After that, present view controller in 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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!