所以你想要做的是,因为 UICollectionView 的工作方式与 UITableView 相同,所以你要做的是创建一个 UICollectionViewCell 的子类,其中包含一个 protocol 以将操作(如按下按钮)发送到视图控制器从不同的角度。在这种情况下,另一个视图是 UICollectionViewCell。
向 UICollectionViewCell 添加协议
添加一个名为 UICustomCollectionViewCell 的新 Cocoa Touch 类,其子类为 UICollectionViewCell。并包含界面构建器文件
头文件 UICustomCollectionViewCell.h
@protocol UICustomCollectionViewCellDelegate;
@interface UICustomCollectionViewCell : UICollectionViewCell
@property ( nonatomic, retain) IBOutlet UIButton *button;
- (IBAction)pressButton:(id)sender;
@property ( assign) id< UICustomCollectionViewCellDelegate> delegate;
@end
@protocol UICustomCollectionViewCellDelegate <NSObject>
@optional
- (void)customCollectionViewCell:(UICustomCollectionViewCell *)cell pressedButton:(UIButton *)button;
@end
实现文件 UICustomCollectionViewCell.m
@implementation UICustomCollectionViewCell
@synthesize delegate;
- (IBAction)pressButton:(id)sender {
if ([delegate respondsToSelector: @selector( customCollectionViewCell:pressedButton:)])
[delegate customCollectionViewCell: self pressedButton: sender];
}
@end
xib 文件 UICustomCollectionViewCell.xib
确保来自 UICustomCollectionViewCell 的连接已连接到来自 Connections Inspector 的按钮:
- 按钮
- -pressButton:
最后,在你的项目中使用这个类
导入类和委托:
#import "UICustomCollectionViewCell.h"
@interface ViewController () < UICustomCollectionViewCellDelegate>
@end
在以下代码中,您将使用 UICustomCollectionViewCell 类而不是 UICollectionViewCell:
UICustomCollectionViewCell *cell;
...
[cell setDelegate: self];
...
return cell;
现在是按下按钮时调用的动作或方法:
- (void)customCollectionViewCell:(UICustomCollectionViewCell *)cell pressedButton:(UIButton *)button {
//action will be here when the button is pressed
}
如果你想知道这个单元格来自哪个 indexPath:
[collectionView indexPathForCell: cell];