【问题标题】:Collection View Cell static variable changes when new cell added添加新单元格时,集合视图单元格静态变量会发生变化
【发布时间】:2016-12-08 04:07:12
【问题描述】:

我正在尝试使用 CollectionView 自定义单元格,我需要从集合视图单元格自定义类本身更新单元格。

这是自定义单元格类

Cell_Obj.h

#import <UIKit/UIKit.h>

@interface Cell_Obj : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *label;

- (void)changeImage;
- (void)updateTextLabelName:(NSString*)str;
@end

Cell_Obj.m

#import "Cell_Obj.h"
static NSString *labelTxt ;
@implementation Cell_Obj{

}

+ (void)initialize {
    if (self == [Cell_Obj class]) {
        labelTxt = [[NSString alloc] init];


    }
}


- (id)initWithFrame:(CGRect)frame
{

    self = [super initWithFrame:frame];
    if (self) {


    }
    return self;
}


- (void)awakeFromNib {

    _label.text = labelTxt;

    [NSTimer scheduledTimerWithTimeInterval:2.0f
                                     target:self
                                     selector:@selector(updateLabel)
                                     userInfo:nil
                                     repeats:YES];
}


- (void)updateLabel
{

    NSString * txt = [NSString stringWithFormat:@"%@",labelTxt];
     _label.text = txt;
}

- (void)updateTextLabelName :(NSString*)str
{

    labelTxt = str;
}

@end

我在 viewCotroller 中添加单元格的位置,

- (void)addCell
{
     Cell_Obj *cell = [[Cell_Obj alloc] init];

    NSString * txt = [NSString stringWithFormat:@"%d",[GridArray count]];
    [cell updateTextLabelName: txt];


    [GridArray addObject:cell];
    [_collection insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:[GridArray count]-1 inSection:0]]];


}

上面代码的问题是,当我添加第一个单元格时,第一个单元格的标签为 0,这很好,但是当我添加第二个单元格并且发生计时器调用时,cell1 和 cell2 的标签值为 1。它应该分别有0,1。

并且似乎单元对象在已创建的单元上发生任何更新时共享静态变量,例如计时器事件。

为什么会发生这种情况,我的方法有什么错误吗?

请告诉我您的宝贵建议。

编辑

根据以下答案,我已将静态变量作为实例变量移动,

@implementation Cell_Obj{
  NSString *labelTxt ;
}

但在 updateLabel labelTxt 内部是零。当我在updateLabel 之前调试updateTextLabelName 时,labelTxt 具有正确的值。

【问题讨论】:

    标签: ios objective-c uicollectionview uicollectionviewcell


    【解决方案1】:

    这是因为collectionview 会重新调用单元格以提高内存效率。因此,当它对单元进行 deque 时,它​​每次都会调用awakeFromNib。所以你应该使用集合视图datasource methods 来更新或设置集合视图控件的内容。你应该实现cellForItemAtIndexPath 在你的标签中设置数据!!

    【讨论】:

    【解决方案2】:

    由于它是一个静态变量,它被所有单元实例共享。 使其工作的方法是从 labelTxt 定义中删除静态。

    另外,静态是什么意思?如果是由于定时器的原因,只需在进行更新之前检查标签不为空的定时器方法,这将解决您的所有问题。

    【讨论】:

    • 感谢您的回复,我已经更改了静态关键字但仍然是相同的结果。
    猜你喜欢
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2021-10-09
    • 1970-01-01
    • 2012-03-08
    相关资源
    最近更新 更多