IOS:当ImageView被触碰时发生的事件

5

我有一张png图片的ImageView,希望实现以下效果:当有人触摸这个ImageView时,它的透明度会变为0.0。是否可能实现这个效果?(不需要按钮)


1
为什么要消除按钮?您可以修改它们的属性,使它们看起来与图像完全相同,同时保留您使用按钮获得的所有功能。 - George Johnston
可能是如何检测UIImageView的触摸事件的重复问题。 - vikingosegundo
5个回答

15

你可以通过使用 addGestureRecognizer 方法将 UITapGestureRecognizer 添加到 UIImageView 中。

代码片段:

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

6
是的,这是可能的。例如,您可以按照以下步骤进行操作:

是的,这是可能的。例如,您可以按照以下步骤进行:

  1. set image view's userInteractionEnabled property to YES - so it will receive touch events
  2. add UITapGestureRecongnizer to it
  3. in gesture handler set view's alpha to 0.0, you can do that with animation as well:

    [UIView animateWithDuration:0.5 animations:^(void){
            imageView.alpha = 0.0f;
        }];
    

4

2

Swift中的代码

在我的情况下,我实现了点击图像的轻拍手势

1 - 通过拖放将图像与ViewController链接起来

@IBOutlet weak var imgCapa: UIImageView!

第二步 - 在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 - 创建一个方法以在图片被点击时执行你想要的操作

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)
}

0
在最近的Xcode中,这非常容易。进入Storyboard,在对象库中搜索“手势”,将您想要的手势拖到图像视图上。然后,您可以将视图层次结构中的手势对象视为被点击的东西,即从那里控制拖动到您的视图控制器以连接事件处理程序。
一旦在那里,您可以根据需要设置alpha值,尽管如果您试图基本上删除图像视图,则应设置imageView.hidden = true / imageView.hidden = YES,因为这将阻止它接收事件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接