IOS:触摸Imageview时的事件
我有一个PNG的ImageView,我想这样做:当有人触摸这个imageview它的alpha更改为0.0,这可能吗? (全部没有button)
对的,这是可能的。 例如,你可以通过以下步骤来做到这一点:
- 设置图像视图的userInteractionEnabled属性为YES – 所以它会收到触摸事件
- 添加UITapGestureRecongnizer它
-
在手势处理器中将视图的alpha设置为0.0,你也可以用animation来做到这一点:
[UIView animateWithDuration:0.5 animations:^(void){ imageView.alpha = 0.0f; }];
你可以使用通过UITapGestureRecognizer
添加到UIImageView
addGestureRecognizer
片段:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTaped:)]; singleTap.numberOfTapsRequired = 1; singleTap.numberOfTouchesRequired = 1; [iv addGestureRecognizer:singleTap]; [iv setUserInteractionEnabled:YES];
和
- (void)imageTaped:(UIGestureRecognizer *)gestureRecognizer { [UIView animateWithDuration:0.5 animations:^(void){ imageView.alpha = 0.0f; }]; }
已经有很多这样的问题了。 谷歌search给了我以下内容:
触及UIImageView的事件处理程序
UIImageView触摸事件
我如何检测UIImageView的触摸事件
Swift中的代码
在我的情况下,我实现了点击图像点击手势
1 – 通过拖放将图像与ViewController链接
@IBOutlet weak var imgCapa: UIImageView!
2 – 在ViewDidLoad方法中实例化UITapGestureRecognizer:
override func viewDidLoad() { super.viewDidLoad() //instance the UITapGestureRecognizer and inform the method for the action "imageTapped" var tap = UITapGestureRecognizer(target: self, action: "imageTapped") //define quantity of taps tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 //set the image to the gesture imgCapa.addGestureRecognizer(tap) }
3 – 创build方法来做点什么,当你点击图像
func imageTapped(){ //write your specific code for what do you want //in my case I want to show other page by specific segue let sumario = self.storyboard?.instantiateViewControllerWithIdentifier("sumarioViewController") as SumarioViewController self.performSegueWithIdentifier("segueSumarioViewController", sender: sumario) }
在最近的Xcode中,这很简单。 进入故事板,在对象库中search“手势”,将你想要的那个拖到图像视图上。 然后,您可以将视图层次结构中的手势对象视为点击事件,即从那里控制拖动到视图控制器以连接事件处理程序。
一旦你可以设置alpha,只要你喜欢,但如果你试图从根本上删除图像视图,你应该设置imageView.hidden = true
/ imageView.hidden = YES
,因为这会阻止它接收事件。