我有一个带有 rootViewController 的 iOS 应用程序。在这个视图控制器中有许多不同的视图。现在我想要这个视图中的集合视图。我该怎么做?我试过的是。向情节提要添加了 uicollection 视图,并将数据源和委托设置为新的 uicollectionview 控制器。基本的东西有效。但我无法从 uicollectionview 控制器视图访问 collectionview。self.collectionview。我是不是忘记了什么?还是有更好的方法来处理这个?
3 回答
You should use a plain view controller, not a collection view controller. The latter will have the collection view as its top level view
property, so you have less flexibility about adding other views to it.
If you want self.collectionView
you need to declare a property. Don't forget to hook it up in interface builder (plus delegate and datasource).
@property (nonatomic, strong) IBOutlet UICollectionView * collectionView;
Of course you can do the same with more than one collection view. However, in your UICollectionViewDataSource
and delegate methods you will have to distinguish the two collection views and provide their respective data or react to user interaction accordinng to which collection view was used.
如果您希望集合视图由您的根视图控制器管理(即其视图层次结构的一部分),那么忘记集合视图控制器并设置集合数据源并委托给您的根视图控制器。然后在根视图控制器类中实现集合视图数据源和委托协议。
@interface ViewController ()
@property (nonatomic, strong) IBOutlet UICollectionView *collectionView;
@end
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(200, 200)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.collectionView setCollectionViewLayout:flowLayout];
在 cellForItemAtIndexPath.. 它应该是下面的东西..
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];
NSString *cellData = [data objectAtIndex:indexPath.row];
static NSString *cellIdentifier = @"cvCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UILabel *titleLabel = (UILabel *)[cell viewWithTag:100];
[titleLabel setText:cellData];
return cell;
}
参考以下文章,很好解释。 http://adoptioncurve.net/archives/2012/09/a-simple-uicollectionview-tutorial/