Detect UIImageView Touch in Swift

前端 未结 3 1311
暖寄归人
暖寄归人 2020-12-08 11:20

How would you detect and run an action when a UIImageView is touched? This is the code that I have so far:

override func touchesBegan(touches:          


        
相关标签:
3条回答
  • 2020-12-08 12:06

    Swift 3

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch:UITouch = touches.first!
            if touch.view == profileImage {
        println("image touched")
    }
    
    }
    
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch:UITouch = touches.first!
            if touch.view == profileImage {
        println("image released")
    }
    
    }
    
    0 讨论(0)
  • 2020-12-08 12:11

    You can put an UITapGestureRecognizer inside your UIImageView using Interface Builder or in code (as you want), I prefer the first. Then you can put an @IBAction and handle the tap inside your UIImageView, Don't forget to set the UserInteractionEnabled to true in Interface Builder or in code.

    @IBAction func imageTapped(sender: AnyObject) {
        println("Image Tapped.")
    }
    

    I hope this help you.

    0 讨论(0)
  • 2020-12-08 12:11

    You can detect touches on a UIImageView by adding a UITapGestureRecognizer to it.

    It's important to note that by default, a UIImageView has its isUserInteractionEnabled property set to false, so you must set it explicitly in storyboard or programmatically.


    override func viewDidLoad() {
        super.viewDidLoad()
    
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTapped)))
    }
    
    @objc private func imageTapped(_ recognizer: UITapGestureRecognizer) {
        print("image tapped")
    }
    
    0 讨论(0)
提交回复
热议问题