在类类型UICollectionViewCell中初始化NSMutableArray

时间:2013-10-16 23:22:58

标签: ios objective-c arrays nsmutablearray uicollectionviewcell

我下载了一个包含下一个类CHTCollectionViewWaterfallCell.h的演示,其中包含以下代码:

#import <UIKit/UIKit.h>

@interface CHTCollectionViewWaterfallCell : UICollectionViewCell

@property (nonatomic, copy) NSString *displayString;
@property (nonatomic, strong) IBOutlet UILabel *displayLabel;
@property (strong, nonatomic) NSMutableArray *windows;

@end

和CHTCollectionViewWaterfallCell.m以及以下内容:

#import "CHTCollectionViewWaterfallCell.h"

@interface CHTCollectionViewWaterfallCell ()
@end

@implementation CHTCollectionViewWaterfallCell
@synthesize windows;

int i=0;


- (void)setDisplayString:(NSString *)displayString {
    windows=[[NSMutableArray alloc]init];
    if (![_displayString isEqualToString:displayString]) {
        _displayString = [displayString copy];
        //self.displayLabel.text = _displayString;

        int n=[_displayString intValue];
        n=n+1;
        self.displayLabel.tag=n;
        NSString* image = [@(n) description];
        UIImage *img =[UIImage imageNamed:[image stringByAppendingString:@".png"]];
        CGSize imgSize = self.displayLabel.frame.size;

        UIGraphicsBeginImageContext( imgSize );
        [img drawInRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        self.displayLabel.backgroundColor=[UIColor colorWithPatternImage:newImage];
        self.displayLabel.userInteractionEnabled=YES;

        UITapGestureRecognizer *tapGesture =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)];
        [self.displayLabel addGestureRecognizer:tapGesture];
    }
}

-(void)labelTap{

    NSLog(@"tapped %d",self.displayLabel.tag);
    int n=self.displayLabel.tag;
    NSString *idWindow=[@(n) description];
    [windows addObject:idWindow];
}

这是来自ViewController的调用并显示类似pinterest的视图,但它只是视图,所以我添加了这些行:

UITapGestureRecognizer *tapGesture =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)];
            [self.displayLabel addGestureRecognizer:tapGesture];

在单击标签时捕获。方法-(void)labelTap,打印单击视图的标签,我遇到问题,因为我想在nsmutablearray中添加点击标签的标签,但是如果我在方法中执行alloc -(void)labelTap,每次单击标签时,数组都会被删除,我试图将其放在(void)setDisplayString:(NSString *)displayString中,但由于一个奇怪的原因,会为标签的每个标签创建一个数组,这意味着存储了1点击了数组中的2在其他数组等...

我希望你能帮助我,这是我正在使用的完整演示:

demo

1 个答案:

答案 0 :(得分:0)

问题看起来像是在- (void)setDisplayString:(NSString *)displayString这个方法的下面写了一行。因此,每次调用它时,都会初始化可变数组。用不同的方法写下面的行。

 windows=[[NSMutableArray alloc]init];