在 Swift 中检测 UIImageView 触摸
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")
}
}
您可以使用 Interface Builder 或在代码中(如您所愿)将 UITapGestureRecognizer
放入 UIImageView
中,我更喜欢第一种。然后你可以在你的 UIImageView
中放置一个 @IBAction
并处理水龙头,不要忘记在 Interface Builder 或代码中将 UserInteractionEnabled
设置为 true
。
@IBAction func imageTapped(sender: AnyObject) {
println("Image Tapped.")
}
希望对你有所帮助。
您可以通过向其添加 UITapGestureRecognizer 来检测 UIImageView
上的触摸。
请务必注意,默认情况下,UIImageView
的 isUserInteractionEnabled
属性 设置为 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")
}
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")
}
}
当 UIImageView
被触摸时,您如何检测并 运行 一个动作?
这是我到目前为止的代码:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch: UITouch = UITouch()
if touch.view == profileImage {
println("image touched")
}
}
您可以使用 Interface Builder 或在代码中(如您所愿)将 UITapGestureRecognizer
放入 UIImageView
中,我更喜欢第一种。然后你可以在你的 UIImageView
中放置一个 @IBAction
并处理水龙头,不要忘记在 Interface Builder 或代码中将 UserInteractionEnabled
设置为 true
。
@IBAction func imageTapped(sender: AnyObject) {
println("Image Tapped.")
}
希望对你有所帮助。
您可以通过向其添加 UITapGestureRecognizer 来检测 UIImageView
上的触摸。
请务必注意,默认情况下,UIImageView
的 isUserInteractionEnabled
属性 设置为 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")
}
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")
}
}