UICollectionView 重新加载数据问题 [英] UICollectionView reload data Issue
问题描述
我在使用 UICollectionView
重新加载数据时遇到问题.我在 viewDidLoad
上有这个数组来填充 UICollectionView.
I have a problem with data reloading using UICollectionView
. I have this array on the viewDidLoad
to fill the 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
并重新加载数据:
I tap the UIButton
and data is reloaded:
[myCollectionView reloadData];
重新加载前后的数据如下所示:
Here how the data looks like before and after the reload:
推荐答案
每次点击重新加载按钮时都会添加一个新标签.您应该添加一次标签并根据更改标签文本.
You add a new label each time you tap the reload button. You should add the label once and change the label text according.
这里是一个简单的例子.
Here a simple example.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = (MyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
forIndexPath:indexPath];
[cell setMyTextLabel:indexPath.row];
return cell;
}
其中 MyCell
将包含一个 UILabel
和一个用于修改其文本的属性.
where MyCell
will contains a UILabel
and a property to modify its text.
我真的建议看看 Fun with UICollectionView @Ben Scheirman 的代码.
I really suggest to take a look at Fun with UICollectionView code by @Ben Scheirman.
希望对您有所帮助.
附:将 myCell
重命名为 MyCell
.类应该以大写字母开头.
P.S. Rename myCell
to MyCell
. A class should start with an uppercase letter.
这篇关于UICollectionView 重新加载数据问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!