尝试以下快速代码(在Xcode 6.3.1中进行了测试):
import UIKit
class KEUITapGesture150427 : UIViewController {
var _myTap: UITapGestureRecognizer?
var _myView: UIView?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor();
_myTap = UITapGestureRecognizer(target: self
, action: Selector("_myHandleTap:"))
_myTap!.numberOfTapsRequired = 1
_myView = UIView(frame: CGRectMake(100, 200, 100, 100))
_myView!.backgroundColor=UIColor.blueColor()
_myView!.layer.cornerRadius = 20
_myView!.layer.borderWidth = 1
_myView!.addGestureRecognizer(_myTap!)
view.addSubview(_myView!)
}
func _myHandleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
println("_myHandleTap(sender.state == .Ended)")
sender.view!.backgroundColor
= UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
}
}
}
请注意,您的目标可以是UIResponder的任何子类,请参见(在Xcode 6.3.1中进行了测试):
import UIKit
class MyTapTarget : UIResponder {
func _myHandleTap2(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
println("_myHandleTap2(sender.state == .Ended)")
sender.view!.backgroundColor
= UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
}
}
}
class KEUITapGesture150427b : UIViewController {
var _myTap: UITapGestureRecognizer?
var _myView: UIView?
var _myTapTarget: MyTapTarget?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor();
_myTapTarget = MyTapTarget()
_myTap = UITapGestureRecognizer(target: _myTapTarget!
, action: Selector("_myHandleTap2:"))
_myTap!.numberOfTapsRequired = 1
_myView = UIView(frame: CGRectMake(100, 200, 100, 100))
_myView!.backgroundColor=UIColor.blueColor()
_myView!.layer.cornerRadius = 20
_myView!.layer.borderWidth = 1
_myView!.addGestureRecognizer(_myTap!)
view.addSubview(_myView!)
}
}