使用UICollectionView进行简单开发
1.类继承<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout> 并添加一个UITableView属性,和一个数组,这个数组是表格上显示的数据
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSArray *array;
@end
2.在- (void)viewDidLoad 初始化collectionView,并添加代理
CGRectMake(0, 0, 300, 600) 的前两个数字是 坐标, 后两个数字是这个collectionView的宽高
- (void)viewDidLoad {
[super viewDidLoad];
//初始化这个数组
self.array = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 300, 600) collectionViewLayout:layout];
//设置collectionView背景是透明色
[self.collectionView setBackgroundColor:[UIColor clearColor]];
//注册行
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
//添加代理
[self.collectionView setDelegate:self];
[self.collectionView setDataSource:self];
//把表格添加到一个控件中
[self.view addSubview:self.collectionView];
//刷新表格
[self.collectionView reloadData];
}
3.添加代理方法
//表格行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.array.count;
}
//表格大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(50,50);
}
//通过刚刚注册的id初始化cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
//indexPath.row表示这是第几行,从0开始
NSString *showStr = self.array[indexPath.row];
[label setText:showStr];
[label setTextAlignment:NSTextAlignmentCenter];
[cell.contentView addSubview:label];
return cell;
}
//行点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSString *showStr = self.array[indexPath.row];
NSLog(@"%@",showStr);
}
//表格行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
return 5.0;
}
//表格列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
return 5.0;
}
附加
UITableView的简单使用>>>iOS UITableView的简单使用
表格嵌套使用>>>ios UITableView行内嵌横向UICollectionView