最好和最实用的解决方案是将你的
UIImageView
嵌入到一个
UIControl
的子类中。
默认情况下,
UIImageView
启用了用户交互。如果你创建一个简单的
UIControl
子类,就可以轻松地将你的图像视图添加到其中,并使用以下方法来实现你想要的效果:
let control = CustomImageControl()
control.addTarget(self, action: "imageTouchedDown:", forControlEvents: .TouchDown)
control.addTarget(self, action: "imageTouchedUp:", forControlEvents: [ .TouchUpInside, .TouchUpOutside ])
这种方法的优点是您可以访问所有不同的触摸事件,节省了自己检测它们所需的时间。
根据您想要做什么,您还可以覆盖
var highlighted: Bool
或
var selected: Bool
以检测用户何时与图像交互。最好以这种方式进行操作,以便您的用户在应用中使用所有控件时具有一致的用户体验。
一个简单的实现看起来会像这样:
final class CustomImageControl: UIControl {
let imageView: UIImageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
imageView.leadingAnchor.constraintEqualToAnchor(leadingAnchor).active = true
imageView.trailingAnchor.constraintEqualToAnchor(trailingAnchor).active = true
imageView.topAnchor.constraintEqualToAnchor(topAnchor).active = true
imageView.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let control = CustomImageControl()
control.translatesAutoresizingMaskIntoConstraints = false
control.imageView.image = ...
control.addTarget(self, action: "imageTouchedDown:", forControlEvents: .TouchDown)
control.addTarget(self, action: "imageTouchedUp:", forControlEvents: [ .TouchUpInside, .TouchUpOutside ])
view.addSubview(control)
control.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
control.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
}
@objc func imageTouchedDown(control: CustomImageControl) {
}
@objc func imageTouchedUp(control: CustomImageControl) {
}
}