正确的添加路径的方法

- (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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值