用户触摸图像时切换图像

时间:2016-02-01 05:36:54

标签: ios swift

我正在尝试在Swift中做两件事:

·当用户触摸图像时,暂时在过滤的图像和原始图像之间切换。

·当用户抬起手指时,切换回来。

但我不知道要使用哪些功能或模块,有什么建议吗?

我有一个图像视图和四个按钮「新照片」,「过滤」,「比较」,「分享」。

3 个答案:

答案 0 :(得分:1)

试试这个

override func viewDidLoad(){

        super.viewDidLoad()
        // add Tap gesture recognizer to ImageView
        let imageView = self.your_imageView
        let tapGestureRecognizer = UILongPressGestureRecognizer(target:self, action:Selector("toggleImage:"))
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tapGestureRecognizer)
}



func toggleImage(sender: UILongPressGestureRecognizer){
        if sender.state == .Began{
           originalImage()
        }else if sender.state == .Ended{
            filteredImage()
        }
 }

它使用UILongPressGestureRecognizer()

答案 1 :(得分:0)

我建议您查看UILongPressGestureRecognizer。

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILongPressGestureRecognizer_Class/index.html#//apple_ref/occ/instp/UILongPressGestureRecognizer/minimumPressDuration

手势开始时,更改正在显示的UIImage。您可以使用UIGestureRecognizerStateEnded检测手势何时结束。我相信你能搞清楚!

答案 2 :(得分:0)

我将最小按下持续时间设置为默认值0.5,使其看起来像一个点按按钮。代码更改以检查过滤后的图像是否为零并且不等于原始图像。我根据状态开始结束来回设置图像视图

    override func viewDidLoad() {
        super.viewDidLoad()

//        adding Tap gesture recognizer to image view
        let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(imageTapped(_:)))
//        Enabling the user interaction for the image view
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(longPressGestureRecognizer)
//        Changing the default minimum press duration from 0.5 to 0.1
        longPressGestureRecognizer.minimumPressDuration = 0.1
    }

//    image tapped function that changes the image view when the user presses on the image view
    func imageTapped(longPressGestureRecognizer: UILongPressGestureRecognizer) {
        if longPressGestureRecognizer.state == .Began {
            imageView.image = originalImage
        } else if longPressGestureRecognizer.state == .Ended {
            if filteredImage != nil && filteredImage != originalImage {
                imageView.image = filteredImage
            }
        }
    }