美文网首页
UIImageView添加点击事件

UIImageView添加点击事件

作者: 蛋蛋是最帅的 | 来源:发表于2016-12-10 16:59 被阅读0次

我们经常会用到UIImageView的点击事件,但是 可以用不同的方法实现,按钮背景图片可以让我们形成类似的触感,但是却很难在上面添加其他内容,而最笨的方法就是在图片上加个透明的按钮,麻烦得不行,所以我们ios中有个对于UIImageView的手势添加方法,不同于按钮的是他有很多手势,不仅限与点击

UIKit中包含了UIGestureRecognizer类,用于检测发生在设备中的手势。UIGestureRecognizer是一个抽象类,定义了所有手势的基本行为,它有下面一些子类用于处理具体的手势:

1、拍击UITapGestureRecognizer (任意次数的拍击)  
2、向里或向外捏UIPinchGestureRecognizer (用于缩放)  
3、摇动或者拖拽UIPanGestureRecognizer  
4、滑动UISwipeGestureRecognizer (以任意方向)  
5、旋转UIRotationGestureRecognizer (手指朝相反方向移动)  
6、长按UILongPressGestureRecognizer 

对于不同类型的手势识别器,具有不同的配置属性。比如UITapGestureRecognizer,可以配置拍击次数。界面接收到手势之后,可以发送一 个消息,用于处理响应手势动作后的任务。当然,不同的手势识别器,发送的消息方法也会有所不同。下面列举几个具体示例代码:

一个手指两次滑动

// 创建一个手势识别器
UITapGestureRecognizer *oneFingerTwoTaps =
  [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerTwoTaps)] autorelease];
 
// Set required taps and number of touches
[oneFingerTwoTaps setNumberOfTapsRequired:2];
[oneFingerTwoTaps setNumberOfTouchesRequired:1];
 
// Add the gesture to the view
[[self view] addGestureRecognizer:oneFingerTwoTaps];

消息方法oneFingerTwoTaps
- (void)oneFingerTwoTaps
{
  NSLog(@"Action: One finger, two taps");
}

一个手指滑动

// 向上滑动
UISwipeGestureRecognizer *oneFingerSwipeUp =
  [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeUp:)] autorelease];
[oneFingerSwipeUp setDirection:UISwipeGestureRecognizerDirectionUp];
[[self view] addGestureRecognizer:oneFingerSwipeUp];

- (void)oneFingerSwipeUp:(UISwipeGestureRecognizer *)recognizer
{
  CGPoint point = [recognizer locationInView:[self view]];
  NSLog(@"Swipe up - start location: %f,%f", point.x, point.y);
}

// 向下滑动
UISwipeGestureRecognizer *oneFingerSwipeDown =
  [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeDown:)] autorelease];
[oneFingerSwipeDown setDirection:UISwipeGestureRecognizerDirectionDown];
[[self view] addGestureRecognizer:oneFingerSwipeDown];

- (void)oneFingerSwipeDown:(UISwipeGestureRecognizer *)recognizer
{
  CGPoint point = [recognizer locationInView:[self view]];
  NSLog(@"Swipe down - start location: %f,%f", point.x, point.y);
}

两个手指捏合

UIPinchGestureRecognizer *twoFingerPinch =
  [[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(twoFingerPinch:)] autorelease];
[[self view] addGestureRecognizer:twoFingerPinch];

- (void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer
{
  NSLog(@"Pinch scale: %f", recognizer.scale);
}

相关文章

网友评论

      本文标题:UIImageView添加点击事件

      本文链接:https://www.haomeiwen.com/subject/pekumttx.html