निम्नलिखित स्विफ्ट कोड का प्रयास करें (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!)
}
}