【问题标题】:Detect UIImageView Touch in Swift在 Swift 中检测 UIImageView 触摸
【发布时间】:2015-06-22 22:29:15
【问题描述】:

UIImageView 被触摸时,您将如何检测并执行操作? 这是我到目前为止的代码:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    var touch: UITouch = UITouch()
    if touch.view == profileImage {
        println("image touched")
    }
}

【问题讨论】:

  • 确保 userInteractionEnabled 设置为 true。我相信false 默认是UIImageView
  • @AdamPro13 它仍然不适用于我上面的代码。

标签: ios swift uiimageview


【解决方案1】:

您可以通过添加UITapGestureRecognizer 来检测对UIImageView 的触摸。

请务必注意,默认情况下,UIImageViewisUserInteractionEnabled 属性设置为 false,因此您必须在情节提要中或以编程方式显式设置它。


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

【讨论】:

    【解决方案2】:

    您可以使用 Interface Builder 或在代码中(如您所愿)将 UITapGestureRecognizer 放入您的 UIImageView 中,我更喜欢第一个。然后你可以在你的UIImageView 中放置一个@IBAction 并处理水龙头,不要忘记在Interface Builder 或代码中将UserInteractionEnabled 设置为true

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

    希望对你有所帮助。

    【讨论】:

    • 如何在“imageTapped”函数中传递额外的参数?
    【解决方案3】:

    斯威夫特 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")
    }
    
    }
    

    【讨论】:

    • 需要在viewDidLoad()方法中添加profileImage.isUserInteractionEnabled = true。
    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多