UICollectionView重载数据问题 [英] UICollectionView reload data Issue

查看:181
本文介绍了UICollectionView重载数据问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用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.

这是一个简单的例子.

- (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.

我真的建议您看看使用UICollectionView进行娱乐 @Ben Scheirman 编写.

I really suggest to take a look at Fun with UICollectionView code by @Ben Scheirman.

希望有帮助.

P.S.将myCell重命名为MyCell.一个类应该以大写字母开头.

P.S. Rename myCell to MyCell. A class should start with an uppercase letter.

这篇关于UICollectionView重载数据问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆