[英]UICollectionView reload data Issue
我有使用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];
这里重新加载之前和之后的数据如何:
每次点击重新加载按钮时都会添加一个新标签。 您应该添加一次标签并更改标签文本。
这是一个简单的例子。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = (MyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
forIndexPath:indexPath];
[cell setMyTextLabel:indexPath.row];
return cell;
}
其中MyCell
将包含一个UILabel
和一个用于修改其文本的属性。
我真的建议看一看乐趣UICollectionView由@Ben Scheirman代码。
希望有所帮助。
PS将myCell
重命名为MyCell
。 一个类应该以大写字母开头。
点击重新加载按钮时,您正在添加标签。 在这种情况下,您一次又一次地添加标签......
所以有三种解决方案:
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;
}
它已经退出了,但这是我的解决方案。
如果您使用自定义collectionviewcell尝试使用'func prepareForReuse()'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.