UICollectionView的實現代碼

jopen 9年前發布 | 22K 次閱讀 iOS開發 移動開發 UICollectionView

首先可以先自定義一個cell

@interface CollectionViewCell : UICollectionViewCell

繼承自UICollectionViewCell

并添加一個ImageView,用autolaytou固定


UICollectionView的實現代碼

記得一定要在這里指定cell的可重用標示符,位置要對,并且和代碼里面設置的ID內容一致


UICollectionView的實現代碼

確保Class指定正確

UICollectionView的實現代碼

下面是AUTOLAYOUT

UICollectionView的實現代碼

記得連線imageView

UICollectionView的實現代碼

上代碼

#import "ViewController.h"
#import "CollectionViewCell.h"
@interface ViewController () <UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic,strong) NSMutableArray *images;
@property (nonatomic,strong) UICollectionView *ucv;
@end
@implementation ViewController
static NSString *const ID = @"cell";//static 代表外部不能訪問,意義上的完全私有(防止extern),const表示ID無法被更改。
-(NSMutableArray *)images
{//image數組的懶加載,將每個圖片的名稱放到數組里面
    if (!_images) {
        _images = [NSMutableArray array];
        for (int i = 1 ; i <= 20; i++) {
            
            NSString *imageName = [NSString stringWithFormat:@"%d",i];
            [_images addObject:imageName];
        }
        
    }
    return  _images;
}
-(UICollectionView *)ucv
{//懶加載一個UICollectionView 并且設置流水效果,
    if (!_ucv) {
        UICollectionViewFlowLayout *flowv = [[UICollectionViewFlowLayout alloc ] init];
        _ucv = [[UICollectionView alloc ] initWithFrame:CGRectMake(0, 20, 320, 80) collectionViewLayout:flowv];
        
    }
    return _ucv;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //設置代理和數據源
    self.ucv.dataSource = self;
    self.ucv.delegate = self;
    //和tablview不同的是要先注冊cell 的nib及可充用標示符
    [self.ucv registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:ID];
    [self.view addSubview:self.ucv];//添加到主視圖咯
    
}
#pragma mark - UICollectionView的代理方法,REquired
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  19;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //使用自定義的cell在collectionView中查找可充用的cell
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    //設置cell的圖片內容,也可以重寫CollectionViewCell 的setImageName方法(定義一個copy的NSString)
    cell.ImageView.image = [UIImage imageNamed:self.images[indexPath.item]];
    NSLog(@"%p",cell);
    return cell;
}
@end

驗證是否重用cell,可以打印cell的地址,在終端find地址0x7fdda2e86820。這里發現地址有三次出現,代表重用了兩次

UICollectionView的實現代碼

來自:http://my.oschina.net/wupengnash/blog/464300

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!