Skip to content

Instantly share code, notes, and snippets.

@dmathewwws
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmathewwws/4b9ff04cffd2776ba56f to your computer and use it in GitHub Desktop.
Save dmathewwws/4b9ff04cffd2776ba56f to your computer and use it in GitHub Desktop.
Delegation should be preferred method. For more information, see http://www.objc.io/issue-7/communication-patterns.html
The custom collection view cell subclass header should look similar to the following code snippet. A couple of things to look for:
It is important that the delegate callbacks include the cell (sender in the following snippet) as one of the parameters. We will need to know which cell invokes the delegate callback in order to find the index path for the cell, which we will then use to retrieve the Photo object to pass to the method to either share or report the photo.
The custom collection view cell subclass should never have or keep a reference to the photo object. Doing so would break MVC pattern where the view should never talk to the model directly.
@import UIKit;
@protocol PanoramaPhotoCollectionViewCellDelegate;
@interface PanoramaPhotoCollectionViewCell : UICollectionViewCell
@property (nonatomic, weak, readonly) UIImageView *imageView;
@property (nonatomic, weak) id <PanoramaPhotoCollectionViewCellDelegate> delegate;
@end
@protocol PanoramaPhotoCollectionViewCellDelegate <NSObject>
- (void)panoramaPhotoCollectionViewCell:(PanoramaPhotoCollectionViewCell *)sender didTapShareButton:(UIButton *)shareButton;
- (void)panoramaPhotoCollectionViewCell:(PanoramaPhotoCollectionViewCell *)sender didTapReportButton:(UIButton *)reportButton;
@end
The view controller should then assign itself to become the delegate of each cell in -collectionView:cellForItemAtIndexPath: call back and implement the two delegate methods, as follows:
- (void)panoramaPhotoCollectionViewCell:(PanoramaPhotoCollectionViewCell *)sender didTapShareButton:(UIButton *)shareButton {
NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
NSInteger photoIndex = indexPath.item;
NSParameterAssert(indexPath && photoIndex < self.photos.count);
Photo *reportedPhoto = self.photos[photoIndex];
[self reportPhoto:reportedPhoto];
}
- (void)panoramaPhotoCollectionViewCell:(PanoramaPhotoCollectionViewCell *)sender didTapReportButton:(UIButton *)reportButton {
NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
NSInteger photoIndex = indexPath.item;
NSParameterAssert(indexPath && photoIndex < self.photos.count);
Photo *sharedPhoto = self.photos[photoIndex];
[self sharePhoto:sharedPhoto];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment