How do you access a UIViewController function from within a UICollectionCell? - swift

I have a function within a UICollectionViewCell that requires access to the
hosting UIViewController. Currently 'makeContribution()' can't be accessed:
What is the proper way of accessing the host UIViewController that has the desired function?

Thanks to the insightful responses, here's the solution via delegation:
...
...
...
{makeContribution}

This is a mildly controversial question - the answer depends a little on your philosophy about MVC. Three (of possibly many) options would be:
Move the #IBAction to the view controller. Problem solved, but it might not be possible in your case.
Create a delegate. This would allow the coupling to be loose - you could create a ContributionDelegate protocol with the makeContribution() method, make your view controller conform to it, and then assign the view controller as a weak var contributionDelegate: ContributionDelegate? in your cell class. Then you just call:
contributionDelegate?.makeContribution()
Run up the NSResponder chain. This answer has a Swift extension on UIView that finds the first parent view controller, so you could use that:
extension UIView {
func parentViewController() -> UIViewController? {
var parentResponder: UIResponder? = self
while true {
if parentResponder == nil {
return nil
}
parentResponder = parentResponder!.nextResponder()
if parentResponder is UIViewController {
return (parentResponder as UIViewController)
}
}
}
}
// in your code:
if let parentVC = parentViewController() as? MyViewController {
parentVC.makeContribution()
}

Well, CollectionView or TableView?
Anyway, Set your ViewController as a delegate of the cell. like this:
#objc protocol ContributeCellDelegate {
func contributeCellWantsMakeContribution(cell:ContributeCell)
}
class ContributeCell: UICollectionViewCell {
// ...
weak var delegate:ContributeCellDelegate?
#IBAction func contributeAction(sender:UISegmentedControl) {
let isContribute = (sender.selectedSegmentIndex == 1)
if isContribute {
self.delegate?.contributeCellWantsMakeContribution(self)
}
else {
}
}
}
class ViewController: UIViewController, UICollectionViewDataSource, ContributeCellDelegate {
// ...
func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
cell = ...
if cell = cell as? ContributeTableViewCell {
cell.delegate = self
}
return cell
}
// MARK: ContributeCellDelegate methods
func contributeCellWantsMakeContribution(cell:ContributeCell) {
// do your work.
}
}

Related

Protocol Function not being called

Please assist. What I'm trying to achieve
is that when I tap on a specific collectionViewCell the ReportDetailsMapController is pushed and my reports[indexPath.item] is sent from MainController to the ReportDetailsMapController.
PROTOCOL:
protocol MainControllerDelegate: class {
func sendReport(data: ReportModel)
}
FIRST VC:
class MainController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var delegate: MainControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let report = reports[indexPath.item]
//When I print(report.name) here. Everything executes correctly
self.delegate?.sendReport(data: report)
self.navigationController?.pushViewController(ReportDetailsMapController(), animated: true)
}
}
SecondVC:
class ReportDetailsMapController: UIViewController, MainControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let mc = MainController()
mc.delegate = self
}
func sendReport(data: ReportModel) {
print(data.name)//This does not execute when ReportDetailsMapController is loaded.
print("Report sent")
}
}
ReportModel:
class ReportModel: NSObject {
var name: String?
var surname: String?
var cellNumber: String?
}
That method is not called because you didn't assign the view controller you're pushing to the delegate property.
When the cell is selected, you could do in this order: initialize the view controller and assign it to the delegate, then call the delegate method and push that view controller:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let report = reports[indexPath.item]
//When I print(report.name) here. Everything executes correctly
let viewController = ReportDetailsMapController()
self.delegate = viewController
self.delegate?.sendReport(data: report)
self.navigationController?.pushViewController(viewController, animated: true)
}
However, I think a simpler and more elegant way would be to simply create that property on the ReportDetailsMapController and inject it before pushing it.
There's a similar question/answer related to that here: passing data from tableview to viewContoller in swift

Can't access to func() in parent VC via Delegate/Protocol

Can't access to function in parent view controller from a child via delegate/protocol. print() doesn't print.
In Child VC I have this:
protocol MyViewControllerDelegate: class {
func requestExpandedView()
}
class MyViewController: UIViewController {
weak var delegate: MyViewControllerDelegate?
...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("\(indexPath) didSelectItemAt")
delegate?.requestExpandedView()
}
}
In Parent VC I have this:
extension MessagesViewController: MyViewControllerDelegate {
func requestExpandedView() {
print("Done") // doesn't print anything
requestPresentationStyle(.expanded)
}
}
What's wrong?
You need to set the delegate of MyViewController when creating its instance, i.e.
let vc = self.storyboard?.instantiateViewController(withIdentifier: "MyViewController") as! MyViewController
vc.delegate = self

Calling a function in a view controller from another view controller

Here is the code with the delegate process suggested...
in main view controller...
protocol FilterDelegate: class {
func onRedFilter()
func onGreenFilter()
func onBlueFilter()
func onUnfiltered()
}
class ViewController: UIViewController, FilterDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
----
// Increase red color level on image by one.
func onRedFilter() {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "filterSegue" {
let dest = segue.destinationViewController as! CollectionViewController
dest.filterDelegate = self
}
}
in collection view controller...
var filterDelegate: FilterDelegate?
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("Cell \(indexPath.row) selected")
guard let filterDelegate = filterDelegate else {
print("Filter delegate wasn't set!")
return
}
switch indexPath.row {
case 0:
filterDelegate.onRedFilter()
case 1:
filterDelegate.onGreenFilter()
case 2:
filterDelegate.onBlueFilter()
case 3:
filterDelegate.onUnfiltered()
default:
print("No available filter.")
}
Right now...the code stops at the guard block and prints the error message. The switch block is not executed on any press of a cell.
Your theory in your second last sentence is correct - when you call storyboard.instantiateViewControllerWithIdentifier in the "child" view controller, you are actually creating an entirely new instance of your main view controller. You are not getting a reference to the existing main view controller, which is why the methods you're calling are not having any effect.
There are several ways to achieve what you're trying to do, including the delegate pattern or using closures. Here's a sketch of what it could look like using a delegate protocol:
protocol FilterDelegate: class {
func onRedFilter()
func onGreenFilter()
func onBlueFilter()
func onUnfiltered()
}
class MainViewController: UIViewController, FilterDelegate {
// implement these as required
func onRedFilter() { }
func onGreenFilter() { }
func onBlueFilter() { }
func onUnfiltered() { }
// when we segue to the child view controller, we need to give it a reference
// to the *existing* main view controller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? ChildViewController {
dest.filterDelegate = self
}
}
}
class ChildViewController: UIViewController {
var filterDelegate: FilterDelegate?
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// ...
guard let filterDelegate = filterDelegate else {
print("Filter delegate wasn't set!")
return
}
switch indexPath.row {
case 0:
filterDelegate.onRedFilter()
case 1:
filterDelegate.onGreenFilter()
case 2:
filterDelegate.onBlueFilter()
case 3:
filterDelegate.onUnfiltered()
default:
print("No available filter.")
}
}
}
Another option would be to provide closures on ChildViewController for every function on MainViewController that the child needs to call, and set them in prepareForSegue. Using a delegate seems a bit cleaner though since there are a bunch of functions in this case.

How to set delegate in a protocol extension

I have multiple view controllers which shows same kind of cells. I want to set delegate in a protocol extension like this:
class ProductsViewController: UIViewController, ProductShowcase {
//other properties
#IBOutlet weak var productCollectionView: UICollectionView!
var dataSource: DataSource!
override func viewDidLoad() {
super.viewDidLoad()
setupDataSource()
setupCollectionView()
}
func didSelectProduct(product: Product) {
print(product)
}
//other functions
}
protocol ProductShowcase: UICollectionViewDelegate {
var dataSource: DataSource! { get set }
var productCollectionView: UICollectionView! { get }
func didSelectProduct(product: Product)
}
extension ProductShowcase {
func setupCollectionView() {
productCollectionView.registerClass(ProductCollectionViewCell.self, forCellWithReuseIdentifier: "productCell")
productCollectionView.dataSource = dataSource
print(self) //prints ProductsViewController
productCollectionView.delegate = self //
print(productCollectionView.delegate) //prints optional ProductsViewController
}
}
extension ProductShowcase {
//this delegate method is not called
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
didSelectProduct(dataSource.dataObjects[indexPath.row])
}
}
When didSelectItemAtIndexPath is implemented in ProductsViewController it gets called. Is there something I missed or is this a wrong approach?
It is a Objective-C interoperability limitation. You are not allowed to implement protocols with optionals function in protocol extension like you wanted (protocols which are from Objective-C type UIKit control's delegates and datasources, etc.). You can have default implementation of only protocol that are written like:
// No, #objc in the front of protocol. (i.e. objc-type protocol)
protocol X {
}

nil value in protocol delegation in tableview and customcell

Im new in Swift, sorry.
I want push value from customcell class to TableViewController class.
But always get "nil".
protocol DetailsDelegate {
func labelDelegateMethodWithString(controller: TableViewController) -> String }
class TableViewController: UITableViewController {
var delegate: DetailsDelegate?
#IBAction func butttonFunc(sender: UIButton) {
let importNumber = delegate!.labelDelegateMethodWithString(self)
println(importNumber)
}
and here my custom cell class:
class TableViewCell: UITableViewCell, UITextFieldDelegate, DetailsDelegate {
func labelDelegateMethodWithString(controller: TableViewController) -> String {
return "efgfsd"
}
What im doing wrong? thanks.