ลองใช้รหัส swift ต่อไปนี้ (ทดสอบใน 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);
}
}
}
โปรดทราบว่าเป้าหมายของคุณอาจเป็น subclass ใด ๆ ของ 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!)
}
}