IOS:触摸Imageview时的事件

时间:2011-10-12 12:54:05

标签: ios xcode uiimageview

我有一个带有png的ImageView,我想这样做:当有人触摸此imageview时,它的alpha变为0.0,是否可能? (全部没有按钮)

5 个答案:

答案 0 :(得分:15)

您可以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;
    }];
}

答案 1 :(得分:6)

是的,有可能。例如,您可以通过以下步骤执行此操作:

  1. 将图片视图的userInteractionEnabled属性设置为YES - 因此它将接收触摸事件
  2. 将UITapGestureRecongnizer添加到其中
  3. 在手势处理程序中将视图的alpha设置为0.0,您也可以使用动画执行此操作:

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

答案 2 :(得分:4)

已经有很多像这样的问题。用谷歌搜索给了我以下内容:

touches event handler for UIImageView

UIImageView Touch Event

how can i detect the touch event of an UIImageView

答案 3 :(得分:2)

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 - 创建方法,以便在单击图像时执行所需操作

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

答案 4 :(得分:0)

在最近的Xcode中,这很容易。进入故事板,在对象库中搜索“手势”,将所需的一个拖到图像视图上。然后,您可以将视图层次结构中的手势对象视为被点击的对象,即从那里控制拖动到视图控制器以连接事件处理程序。

在那里,您可以根据需要设置Alpha,但如果您尝试基本上删除图片视图,则应设置imageView.hidden = true / imageView.hidden = YES,因为这会阻止它接收事件