【发布时间】: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