在iOS中以编程方式单击UIImageView上的事件
我从代码显示的图像这里是代码
UIImageView *preArrowImage =[[UIImageView alloc]init ]; preArrowImage.image =[UIImage imageNamed:@"arrowprev.png"]; preArrowImage.frame = CGRectMake(20, 60, 10, 30); [self.view addSubview:preArrowImage];
我想以编程方式处理preArrowImage上的触摸事件。
Objective-C的
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)]; singleTap.numberOfTapsRequired = 1; [preArrowImage setUserInteractionEnabled:YES]; [preArrowImage addGestureRecognizer:singleTap]; -(void)tapDetected{ NSLog(@"single Tap on imageview"); }
SWIFT 3
let preArrowImage : UIImageView // also give it frame let singleTap = UITapGestureRecognizer(target: self, action: Selector("tapDetected")) singleTap.numberOfTapsRequired = 1 // you can change this value preArrowImage.isUserInteractionEnabled = true preArrowImage.addGestureRecognizer(singleTap) //Action func tapDetected() { print("Imageview Clicked") }
只需在图像上添加一个UITapGesture
,但记得启用UserInteraction 。
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)]; [preArrowImage addGestureRecognizer:singleTap]; [preArrowImage setMultipleTouchEnabled:YES]; [preArrowImage setUserInteractionEnabled:YES];
现在在斯威夫特!
let singleTap = UITapGestureRecognizer(target: self, action: Selector("tapDetected")) singleTap.numberOfTapsRequired = 1 preArrowImage.userInteractionEnabled = true preArrowImage.addGestureRecognizer(singleTap) //Action func tapDetected() { println("Single Tap on imageview") }
在视图控制器中使用视图板和视图。
select其中一个手势识别器后,将其拖动到您的控制器。
现在将显示在“文档大纲”和视图控制器xib的标题中。
将手势拖动到UILable
在头文件中创buildIBAction方法
现在将其从处理程序拖到xib中的手势图标
Swift 3
在UIImageView上启用UserInterAction
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) if let touch = touches.first { if touch.view == self.imgVwPostPreview { //image View property //Do your actions //self.delegate?.didClickOnCellImageView(indexPath: self.cellIndexPath!) } } }
如果您的UIImageView是从故事板或笔尖获得的IBOutlet,则可以将UIGestureRecognizer添加到图像视图,启用用户交互并将IBAction连接到手势识别器。
有关更多信息请查看我对这个问题的回答: 如何在故事板上使UIImageView可点击(swift)
这是另一个select:作弊。
我的意思是,侧面思考。
设置你的UIImage你想如何,裁剪,方面适合,不pipe。
用UIView(等号,位置等)
将背景设置为clearcolour,将类设置为UIControl。
把事情的内幕指向你的处理者,瞧。