繁体   English   中英

在Swift中检测UIImageView Touch

[英]Detect UIImageView Touch in Swift

触摸UIImageView时,您将如何检测和运行动作? 这是我到目前为止的代码:

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

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

重要的是要注意,默认情况下, 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")
}

您可以使用Interface Builder将UITapGestureRecognizer放置在UIImageView内,也可以将其UITapGestureRecognizer在代码中(根据需要),我更喜欢第一个。 然后,您可以放置​​一个@IBAction并处理UIImageView内的轻@IBAction ,不要忘记在Interface Builder或代码中将UserInteractionEnabled设置为true

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

希望对您有所帮助。

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM