项目需要做一个书架功能,期间选取了tableview做控件,还有很多三方的框架,但是深入使用之后发现collectionView的优势在做这样的需求时还是最合适的,一点小感悟把,就想选择控件一样,很多东西其实方向错了,再怎么努力也是徒劳的。鸡汤到此为止,入正题。
首先是建立collectionView和一些他的必要代理,代码如下。
其中cellForItems这个代理中的ShelfLabel是自己定义的一个继承与UICollectionViewCell的类,因为CollectionViewCell没有默认的,所以需要自定义。因为需要正常状态点击跳转书籍阅读页面,长按出现书架编辑页面,所以需要加一个长按手势在这个代理中。
/******************************************CollectionView的创建和代理**************************/
/******************************************CollectionView的创建和代理**************************/
/******************************************CollectionView的创建和代理**************************/
- (void)CreatColletionViewAsShelf
{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
CollectVShelf = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight-108) collectionViewLayout:flowLayout];
[CollectVShelf registerNib:[UINib nibWithNibName:@"HomeShelfCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:STRIDENT];
CollectVShelf.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1];
[self.view addSubview:CollectVShelf];
CollectVShelf.delegate = self;
CollectVShelf.dataSource = self;
}
//共有多少个单元格
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return arrIMG.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
HomeShelfCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:STRIDENT forIndexPath:indexPath];
[cell.ShelfimgView setImageWithURL:[NSURL URLWithString:arrIMG[indexPath.row]] placeholderImage:[UIImage imageNamed:@""]];
cell.Shelflabel.text = arrBookName[indexPath.row];
cell.ShelfimgView.userInteractionEnabled = YES;
cell.m_checkImageView.image = [UIImage imageNamed:@""];
cell.tag = indexPath.row;
UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(tapGes:)];
[cell addGestureRecognizer:tap];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(100, 170);
}
//边距