-->

Presenting a View Controller with a button in a UI

2020-08-11 10:19发布

问题:

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