- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
CGFloat x = 0,y = 0;
//通过循环往 scrollview 上添加缩略图,为了能让UIImagView能响应点击事件,首先打开UIImageView的用户交互(userInteractionEnabled),并添加一个UITapGestureRecognizer
for (int i = 1; i < 20; i++) {
NSString *imageName = [NSString stringWithFormat:@"image%d",i];
NSString *png = @"png";
NSString *jpg = @"jpg";
NSString *jpeg = @"jpeg";
//从程序包中获得图片的完整路径(NSBundle代表程序包)
NSString *filePath = [[NSBundle mainBundle] pathForResource:imageName ofType:png];
//根据路径创建图片
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
if (image == nil) {//如果创建图片失败(即:图片不是png,看是否是jpg),重新创建
filePath = [[NSBundle mainBundle] pathForResource:imageName ofType:jpg];
image = [[UIImage alloc] initWithContentsOfFile:filePath];
}
if (image == nil) {//如果创建图片失败(即:图片不是jpg,看是不是jpeg),重新创建
filePath = [[NSBundle mainBundle] pathForResource:imageName ofType:jpeg];
image = [[UIImage alloc] initWithContentsOfFile:filePath];
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 100, 150)];
imageView.image = image;
imageView.tag = 100 + i;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[imageView addGestureRecognizer:tap];
[self addSubview:imageView];
[image release];
[tap release];
[imageView release];
x += 110;
if (x >= 320) {
x = 0;
y += 160;
}
}
self.contentSize = CGSizeMake(320, y + 150);
// Initialization code
}
return self;
}
正确的添加路径的方法
最新推荐文章于 2023-06-01 10:42:34 发布