UICollectionView重新加载数据问题
我有使用UICollectionView
重新加载数据的问题。 我有这个数组viewDidLoad
填充UICollectionView.
array = [[NSMutableArray alloc] init]; [array addObject:@"1"]; [array addObject:@"2"]; [array addObject:@"3"]; [array addObject:@"4"]; [array addObject:@"5"]; [array addObject:@"6"];
和方法:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { NSString *cellIdentifier = @"Cell"; //cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; myCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 100, 20)]; [titleLabel setText:[array objectAtIndex:indexPath.row]]; titleLabel.textColor = [UIColor whiteColor]; titleLabel.backgroundColor = [UIColor clearColor]; [cell addSubview:titleLabel]; return cell; }
我点击UIButton
并重新加载数据:
[myCollectionView reloadData];
在这里,重载之前和之后的数据看起来如何:
每次点击重新加载button时都会添加一个新标签。 您应该添加标签一次,并根据更改标签文本。
这里有个简单的例子。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { MyCell *cell = (MyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; [cell setMyTextLabel:indexPath.row]; return cell; }
其中MyCell
将包含一个UILabel
和一个属性来修改其文本。
我真的build议看看@Ben Scheirman的UICollectionView代码的乐趣 。
希望有所帮助。
PS将myCell
重命名为MyCell
。 一个类应该以大写字母开头。
点击重新加载button时,您正在添加标签。 在这种情况下,你一次又一次地添加标签…
所以有三个解决scheme:
- 使您的细胞可重复使用
- 在重载方法中从超视图中删除你的单元格。
- 您可以检查标签的
text
长度是否不等于零。 在这种情况下,不需要添加该标签并更改文本。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath]; dispatch_async(dispatch_get_main_queue(), ^{ // ********* Changed ******* for (UIView *v in [cell.contentView subviews]) [v removeFromSuperview]; // ********** Changed ********** if ([self.collectionviewFlow.indexPathsForVisibleItems containsObject:indexPath]) { NSString *img_name=[NSString stringWithFormat:@"%@_thumb%d.png",self.VaritiesName,(int)indexPath.row+1]; imageVw=[[UIImageView alloc]initWithImage:[UIImage imageNamed: img_name]]; imageVw.frame=CGRectMake(10,10,100,100); [cell.contentView addSubview:imageVw]; } }); cell.backgroundColor=[UIColor clearColor]; return cell; }
这是退出晚,但这是我的解决scheme。
如果您使用自定义collectionviewcell尝试使用“func prepareForReuse()”