自定義的UICollectionViewCell 的步驟:
1. collectionView.delegate = self;
2. 設置 @interface ViewController ()3. #pragma mark -監聽按鈕點擊
-(void)collectionView: (UICollectionView *)collectionView didSelectedItemAtIndexPath:( NSIndexPath *)indexPath
{
NSLog(@“——%zd”,indexPath.item);
}
4. 自定義cell XMGImageCell 繼承自UICollectionViewCell 最好也設置一下XIB 文件。
5. 拖入一個imageview 放入cell 設置約束 cell 設置標識identifier(屬性4) 例如:photo
6. 把一個image view 拖入XMGImageCell 項目中 取名imageView; (@property(weak, nonatomic) IBOutlet UIImageView * imageView;)
7. 拖入圖片數據,放入xcassets
8.導入文件 #import “XMGPhotoCell.h”
9.設置 static NSString * const XMGPhotoId =@“photo”;
10. viewDidLoad 中
//注冊 [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([XMGPhotoCell class]) bundle:nil ] forCellWithReuseIdentifier: XMGPhotoId]
11. XMGPhotoCell.h 中 設置屬性 @property (nonatomic, copy )NSString *imageName;
12. // 設置cell 的內容
-(NSIntege) collectionView: (UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
// 有多少個cell
return 20 ;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//創建cell
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:XMGCellId forIndexPath:indexPath];
//cell的背景顏色
//cell.backgroundColor =[UIColor orangeColor];
cell.imageName = [NSString stringWithFormat: @"zd”,indexPath.item + 1];
return cell;
}
@end
13. - (void)setImageName:(NSString *)imageName
{
_imageName = [imageName copy];
self.imageView.image = [UIImage imageNamed: imageName];
}
寫到這 就可以正常顯示圖片到cell 中了 還有些細節處理 往下看
需求: 要讓圖片四周邊框要有白色間距10:
解決:可以設置自定義cell imageview 與邊的約束。
解決方法2 : 給imageView 加一個圖層邊框就可以了。
-(void)awakeFromNib {
self.imageView.layer.borderColor = [ UIColor whiteColor].CGColor ;
self.imageView.layer.borderWhite = 10;
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。