[英]Collection View Cell static variable changes when new cell added
我试图使用use 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
之前updateLabel
updateTextLabelName
时, labelTxt
具有正确的值。
由于它是一个静态变量,因此它被所有单元实例共享。 使其起作用的方法是从labelTxt定义中删除静态变量。
另外,它是静态的意味着什么? 如果是由于计时器造成的,则只需在进行更新之前检查timer方法中的label不为null即可解决所有问题。
这是因为collectionview继续处理单元以提高其内存效率。 因此,每次抽出时间,在使单元出队时,它将调用awakeFromNib
。 因此,您应该使用集合视图datasource methods
来更新或设置集合视图控件的内容。 您应该实现cellForItemAtIndexPath
以在标签中设置数据!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.