我有一张png图片的ImageView,希望实现以下效果:当有人触摸这个ImageView时,它的透明度会变为0.0。是否可能实现这个效果?(不需要按钮)
我有一张png图片的ImageView,希望实现以下效果:当有人触摸这个ImageView时,它的透明度会变为0.0。是否可能实现这个效果?(不需要按钮)
你可以通过使用 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;
}];
}
是的,这是可能的。例如,您可以按照以下步骤进行:
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;
}];
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)
}
imageView.hidden = true
/ imageView.hidden = YES
,因为这将阻止它接收事件。