次のコードを使用して、次のクラス 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は他の配列に保存されます...
あなたが私を助けてくれることを願っています.これは私が使用している完全なデモです: