背景颜色未分配和单元重用问题

时间:2017-02-01 04:59:57

标签: ios objective-c uitableview uicollectionview

我制作了一个简单的应用,UICollectionView嵌入了UITableViewCell。 但是,当应用程序运行时,UICollectionViewCell不会为此指定颜色,稍后会重复使用。

TableViewCell CollectionViewCell 分别设计在他们的笔尖中 - CustomTableViewCell.xibCustomCollectionViewCell.h

同一行中的单元格必须具有相同的颜色,即TableView第一行中的红色单元格,TableView第二行中的绿色单元格等等。

我的代码在

下面

ViewController.h

@interface ViewController:UIViewController <UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *userTableView;
@property(strong,nonatomic) NSArray* color;
@end

ViewController.m

- (void)viewDidLoad{
 [super viewDidLoad];
_color=[[NSArray alloc] initWithObjects:[UIColor redColor],[UIColor  greenColor],[UIColor blueColor],[UIColor purpleColor],[UIColor orangeColor],[UIColor cyanColor],[UIColor lightGrayColor],[UIColor   magentaColor], nil];
[_userTableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"TVCell"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 8;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TVCell"];
CustomCollectionViewCell *cCell=(CustomCollectionViewCell*)[cell.userCollectionView cellForItemAtIndexPath:indexPath];
cCell.backgroundColor=[_color objectAtIndex:indexPath.row];
return cell;
}

CustomTableViewCell.h

@interface CustomTableViewCell : UITableViewCell  <UICollectionViewDelegate, UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UICollectionView   *userCollectionView;
@end

CustomTableViewCell.m

@implementation CustomTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
[_userCollectionView registerNib:[UINib nibWithNibName:@"CustomCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CVCell"];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 20;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CustomCollectionViewCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"CVCell" forIndexPath:indexPath];
return cell;
}

以下是运行项目后的UI图像

enter image description here

我该如何解决这个问题? 请帮忙。

同一列中的单元格必须具有相同的颜色,即TableView第一列中的红色单元格,TableView第二列中的绿色单元格等等。

1 个答案:

答案 0 :(得分:0)

UITableViewDelegate方法cellForRow中注册collectionViewCell并设置其delegatedatasource,然后在UICollectionViewDelegate方法cellForItemAtIndexPath中设置背景你的collectionView Cell。如果在控制器中分配collectionView委托,将会更好,更容易管理。

希望它有所帮助。