View a view controller using a button in a UITableViewCell programmatically (Swift)

I try to do this when the user clicks on a table cell in my table view, he transfers them to the new view controller. More specifically, when a user clicks on a userโ€™s username, he should relate them to this user profile. the username is the table view cell, and the profile is the new view controller. I thought that you need to use ".presentViewController (vc, animated: true, completion: noil) for this, however, when I do this, it says:" myCell does not have a member named .presentViewController " Below is a screenshot of the issue

If anyone can help me solve this problem, we will be very grateful

+12
source share
4 answers

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

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

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

So: Get a click on a button inside a cell of a user interface table view

+18
source

Denying responses works, but the syntax is old. From Swift 4 :

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

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) 
+2
source

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

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

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

After that, submit the 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) } 
0
source

All Articles