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

烂漫一生 提交于 2019-12-06 20:12:48

问题


I am trying to make it where when a user clicks on a table view cell in my table view it takes them to a new view controller. More specifically, when a user clicks on a persons username it should take them to that users profile. the username being the table view cell and the profile being the new view controller. I thought the way to do this was to use the ".presentViewController(vc, animated: true, completion: nil) however when i do this it says "myCell does not have a member named .presentViewController"

If anyone could help me solve this problem it'd be greatly appreciated


回答1:


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




回答2:


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

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



回答3:


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)



回答4:


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


来源:https://stackoverflow.com/questions/30736391/presenting-a-view-controller-with-a-button-in-a-uitableviewcell-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!