I have a button in my UICollectionViewCell.swift: I want, based on certain parameters for it to be able to present an alert.
class CollectionViewCell: UICollectionViewCell {
var collectionView: CollectionView!
@IBAction func buttonPressed(sender: UIButton) {
doThisOrThat()
}
func doThisOrThat() {
if x == .NotDetermined {
y.doSomething()
} else if x == .Denied || x == .Restricted {
showAlert("Error", theMessage: "there's an error here")
return
}
}
func showAlert(title: String, theMessage: String) {
let alert = UIAlertController(title: title, message: theMessage, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.collectionView!.presentViewController(alert, animated: true, completion: nil)
}
On the self.collectionView!.presentViewController line I get a break:
fatal error: unexpectedly found nil while unwrapping an Optional value
I'm guessing that this has someting to do with how CollectionView is being used - I don't totally understand optionals yet. I know that a UICollectionCell can't .presentViewController - which is why I'm trying to get UICOllectionView to do it.
How do I make this work? I've thought of using an extension but don't know how to make UICOllectionViewCell adopt .presentViewController
Any ideas?
The collection view cell should not depend on knowledge of its parent view or view controller in order to maintain a functional separation of responsibilities that is part of a proper app architecture.
Therefore, to get the cell to adopt the behavior of showing an alert, the delegation pattern can be used. This is done by adding a protocol to the view controller that has the collection view.
@protocol CollectionViewCellDelegate: class {
func showAlert()
}
And having the view controller conform to that protocol:
class MyViewController: UIViewController, CollectionViewCellDelegate {
Also add a delegate property to the cell:
weak var delegate: CollectionViewCellDelegate?
Move the showAlert() function inside your collection view controller.
When you make a cell, assign the delegate for the cell to the collection view controller.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// Other cell code here.
cell.delegate = self
When it is time to show the alert, have the cell call
delegate.showAlert()
The alert will then be presented on the collection view controller because it has been set as the delegate of the collection view cell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With