UICollectionView重载数据问题

The*_*her 4 objective-c ios uicollectionview uicollectionviewcell

我有使用数据重新加载的问题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"];
Run Code Online (Sandbox Code Playgroud)

和方法:

-(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;
}
Run Code Online (Sandbox Code Playgroud)

我点击UIButton并重新加载数据:

[myCollectionView reloadData];
Run Code Online (Sandbox Code Playgroud)

这里重新加载之前和之后的数据如何: 之前

后

Lor*_*o B 12

每次点击重新加载按钮时都会添加一个新标签.您应该添加一次标签并更改标签文本.

这是一个简单的例子.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    MyCell *cell = (MyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
                                                                               forIndexPath:indexPath];
    [cell setMyTextLabel:indexPath.row];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

where MyCell将包含一个UILabel和一个属性来修改其文本.

我真的建议看一看乐趣UICollectionView通过代码@Ben Scheirman.

希望有所帮助.

PS重命名myCellMyCell.一个类应该以大写字母开头.