ilovecomputer
ilovecomputer

Reputation: 4708

Toggle image when the user touch the image

I'm trying to do two things in Swift:

· When the user touches the image, toggle between the filtered, and original images temporarily.

· When the user lifts their finger, toggle back.

But I don't know what functions or modules to use, any suggestions?

I have got a image View and four buttons 「New Photo」,「Filter」,「Compare」,「Share」.

Upvotes: 0

Views: 1319

Answers (3)

Akarsh SEGGEMU
Akarsh SEGGEMU

Reputation: 2561

I set the minimum press duration to 0.1 from default 0.5 to make it look like a tap button. Code changes to check if the filtered image is not nil and it is not equal to the original image. I set back and forth the image view according the state began and end

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

Upvotes: 0

Encio Peter
Encio Peter

Reputation: 329

Try this

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

It uses UILongPressGestureRecognizer()

Upvotes: 1

mcfisty
mcfisty

Reputation: 207

I would recommend looking into UILongPressGestureRecognizer.

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

When the gesture begins, change the UIImage being displayed. You can detect when the gesture ends with UIGestureRecognizerStateEnded. I'm sure you'll figure it out!

Upvotes: 0

Related Questions