使用手势(UITapGestureRecognizer)获取照片墙上首次点击图片

it2025-06-01  80

前言

在写shareAPP时需要将选择的第一个图片返回至上层界面,首先得获取首次被点击的图片,通过查资料得知可设一个UIImage属性,将手势点击的第一个图片传给它。但我不太会同时使用UIButton和手势在同一个UIImageView上,使用该手势好像影响了button的实现,我后来还是将手势去掉了。可能以后会使用到,还是记录下来吧。

思路

1.创建一个照片墙,可以看这篇 2.每张图片上都添加手势,创建点击手势函数 3.在手势函数中,若创建的UIImage属性值为nil,则将点击的图片赋值给它

代码

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view //创建照片墙 //创建一个UIScrollView UIScrollView *imageScrollView = [[UIScrollView alloc] init]; imageScrollView.frame = CGRectMake(10, 0, 395, 600); imageScrollView.contentSize = CGSizeMake(395, 600 * 1.5); imageScrollView.showsVerticalScrollIndicator = NO; //打开交互模式 imageScrollView.userInteractionEnabled = YES; for(int i = 0; i < 30; i++){ //加入图片 NSString *strName = [NSString stringWithFormat:@"image-%d.jpg", i + 1]; UIImage *image = [UIImage imageNamed: strName]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.frame = CGRectMake(2 + (i % 4) * 100, (i / 4) * 110 + 5 , 95, 105); [imageScrollView addSubview: imageView]; //打开图片的交互模式 imageView.userInteractionEnabled = YES; //创建手势 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pressTap:)]; //单次点击 tap.numberOfTapsRequired = 1; //单个手指 tap.numberOfTouchesRequired = 1; //将手势添加在imageView中 [imageView addGestureRecognizer:tap]; } [self.view addSubview:imageScrollView]; } //手势点击函数 - (void)pressTap: (UITapGestureRecognizer *) tap{ UIImageView *imageView = [[UIImageView alloc] init]; //imageView为手势点击的imageView imageView = (UIImageView *)tap.view; //确定为第一次点击 if(!_image){ _image = [[UIImage alloc] init]; _image = imageView.image; } }
最新回复(0)