在开发中,或许美工给你的UI设计图 上有很复杂的界面设计,比如一个视图上明显是tableview 但是上面也有collectionview 这时候怎么办,不要慌,下面我教你怎么写。
1首先,创建整体UI界面
- (void)buildUI{
_tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VIEW_Width, VIEW_Height)];
_tableview.delegate = self;
_tableview.dataSource = self;
_tableview.rowHeight = 200;
_tableview.backgroundColor = [UIColor greenColor];
[self.view addSubview:_tableview];
_collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 200, VIEW_Width, 200) collectionViewLayout:[self customLayout]];
_collectionView.backgroundColor = [UIColor redColor];
_collectionView.delegate = self;
_collectionView.dataSource = self;
[_collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
[_tableview addSubview:_collectionView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 3;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 0) {
NSLog(@"000000");
}else if (indexPath.section == 1){
NSLog(@"index11111");
}else{
NSLog(@"index22");
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *idenfier = @"cellID";
if (indexPath.section == 1) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idenfier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idenfier];
}
cell.imageView.image = [UIImage imageNamed:@"af4"];
return cell;
}else{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idenfier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idenfier];
}
cell.imageView.image = [UIImage imageNamed:@"af3"];
return cell;
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 4;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 10;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.item == 0) {
NSLog(@"0");
}else if(indexPath.item == 1){
NSLog(@"1");
}else{
NSLog(@"2");
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"hah";
}
- (CGSize )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(VIEW_Width / 3,120);
}
这样 一个在tableview上cell自定义的collection view就写好了 其实很简单