私はUIViewを持っています、そして私はそれにタップジェスチャーを追加しました:
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
tap.delegate = self
myView.addGesture(tap)
私はテストファイルでプログラム的にそれを呼び出そうとしています。
sendActionForEvent
私はこの機能を使っていますが、うまくいきません。
myView.sendActionForEvent(UIEvents.touchUpDown)
インスタンスに送信された認識されていないセレクタが表示されます。
どうすればこの問題を解決できますか?
前もって感謝します
以下のように、ターゲットとアクションでUITapGestureRecognizer
を初期化する必要があります。
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
tap.delegate = self // This is not required
myView.addGestureRecognizer(tap)
それから、tapイベントが発生するたびに呼び出されるハンドラを実装する必要があります。
@objc func handleTap(sender: UITapGestureRecognizer? = nil) {
// handling code
}
だから今あなたのタップジェスチャーレコグナイザーイベントハンドラを呼び出すことはメソッドを呼び出すのと同じくらい簡単です:
handleTap()
Swift 3 solutionを探している人のために
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
self.view.addSubview(view)
// function which is triggered when handleTap is called
func handleTap(_ sender: UITapGestureRecognizer) {
print("Hello World")
}
Swift 4 の場合:
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
self.view.addSubview(view)
// function which is triggered when handleTap is called
@objc func handleTap(_ sender: UITapGestureRecognizer) {
print("Hello World")
}
Swift 4では、トリガーされた関数がObjective-Cから呼び出し可能であることを明示的に示す必要があるので、@ objcもあなたのhandleTap関数を追加する必要があります。
ここで@ ALi Beadleの答えを参照してください。 Swift 4ジェスチャーを追加する:@ vsjjをオーバーライドする
ちょっと注意 - ビューで対話を有効にすることを忘れないでください。
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
view.addGestureRecognizer(tap)
// view.userInteractionEnabled = true
self.view.addSubview(view)
STEP:1
@IBOutlet var viewTap: UIView!
STEP:2
var tapGesture = UITapGestureRecognizer()
STEP:3
override func viewDidLoad() {
super.viewDidLoad()
// TAP Gesture
tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myviewTapped(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
viewTap.addGestureRecognizer(tapGesture)
viewTap.isUserInteractionEnabled = true
}
STEP:4
func myviewTapped(_ sender: UITapGestureRecognizer) {
if self.viewTap.backgroundColor == UIColor.yellow {
self.viewTap.backgroundColor = UIColor.green
}else{
self.viewTap.backgroundColor = UIColor.yellow
}
}
_ output _
タップジェスチャーの実装
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "touchHappen")
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)
タップが認識されたときにこの関数を呼び出します。
func touchHappen() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
self.view.endEditing(true)
}
For Swift 3用の更新プログラム
let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchHappen(_:)))
view.addGestureRecognizer(tap)
view.userInteractionEnabled = true
func touchHappen(_ sender: UITapGestureRecognizer) {
print("Hello Museer")
}
スイフト4
let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchTapped(_:)))
self.view.addGestureRecognizer(tap)
@objc func touchTapped(_ sender: UITapGestureRecognizer) {
}
これがSwift 3でどのように機能するかです。
@IBOutlet var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap))
myView.addGestureRecognizer(tap)
}
func handleTap() {
print("tapped")
}
私はSwift上のXcode 6.4で作業しました。下記参照。
var view1: UIView!
func assignTapToView1() {
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
// tap.delegate = self
view1.addGestureRecognizer(tap)
self.view .addSubview(view1)
...
}
func handleTap() {
print("tap working")
view1.removeFromSuperview()
// view1.alpha = 0.1
}
スイフト4のための完全な答え
ステップ1:ビューのアウトレットを作成する
@IBOutlet weak var rightViewOutlet: UIView!
ステップ2:タップジェスチャを定義する
var tapGesture = UITapGestureRecognizer()
ステップ3:ObjC関数を作成する(ビューがタップされたときに呼び出される)
@objc func rightViewTapped(_ recognizer: UIGestureRecognizer) {
print("Right button is tapped")
}
ステップ4:viewDidLoad()内に以下を追加する
let rightTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.rightViewTapped(_:)))
rightViewOutlet.addGestureRecognizer(rightTap)
次のように、ターゲットとアクションを使用してUITapGestureRecognizerを初期化する必要があります。
let tap = UITapGestureRecognizer(target: self, action: "handleTap:")
tap.delegate = self
myView.addGestureRecognizer(tap)
それから、tapイベントが発生するたびに呼び出されるハンドラを実装する必要があります。
func handleTap(sender: UITapGestureRecognizer) {
// handling code
}
Objective Cのコードが必要な場合は、
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; // Declare the Gesture.
gesRecognizer.delegate = self;
[yourView addGestureRecognizer:gesRecognizer]; // Add Gesture to your view.
// Declare the Gesture Recognizer handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
NSLog(@"Tapped");
}
または、Swiftのコードを以下に示します。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Add tap gesture recognizer to view
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
myView.addGestureRecognizer(tapGesture)
}
// this method is called when a tap is recognized
func handleTap(sender: UITapGestureRecognizer) {
print("tap")
}
}
let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
frontView.addGestureRecognizer(tap)
// Make sure this is not private
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
}
スイフト4
まず、UITapGestureRecognizerのオブジェクトを作成します
var tapGesture = UITapGestureRecognizer()
2番目のステップはUITapGestureReconizerを初期化することです。ユーザー操作を有効にしてから追加します。
override func viewDidLoad() {
super.viewDidLoad()
tapGesture = UITapGestureRecognizer(target: self, action: #selector(YourViewController.myviewTapped(_:)))
infosView.isUserInteractionEnabled = true
infosView.addGestureRecognizer(tapGesture)
view.addSubview(infosView)
}
第三に、メソッドを作成する
@objc func myviewTapped(_ recognizer: UIGestureRecognizer) {
print("button is tapped")
}
次の拡張子を試してください
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
そしてそれを使う:
submitBtn.addTapGesture {
//your code
}
セルにも使えます
cell.addTapGesture {
//your code
}
次の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);
}
}
}
あなたのターゲットは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!)
}
}
私はSwift 2.2上のXcode 7.3.1で作業しました。下記参照。
func addTapGesture() {
let tap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.handleTap))
tap.numberOfTapsRequired = 1
self.myView.addGestureRecognizer(tap)
}
func handleTap() {
// Your code here...
}
xCode 9.3、Swift 4.0
class BaseVC: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var iView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let clickUITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onSelect(_:)))
clickUITapGestureRecognizer.delegate = self
iView?.addGestureRecognizer(tap)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return true
}
@IBAction func onSelect(_ sender: Any) {
}
}
問題の原因となっている点を2つ指定したいと思いました。
内側ViewDidLoad
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
self.imgMainAdView.isUserInteractionEnabled = true
self.imgMainAdView.addGestureRecognizer(tapGestureRecognizer)
//MARK: - Image Tap Method -
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
print("Tapped")
if let url = URL(string: self.strMAinAdvLink)
{
UIApplication.shared.open(url, options: [:])
}
}
呼び出し目的
@IBAction func btnCall1Action(_ sender: Any)
{
let text = self.strPhoneNumber1!
let test = String(text.filter { !" -()".contains($0) })
UIApplication.shared.openURL(NSURL(string: "tel://\(test)")! as URL)
}
メール目的
MFMailComposeViewControllerDelegate
@IBAction func btnMailAction(_ sender: Any)
{
let strEmail = SAFESTRING(str: (self.dictEventDetails?.value(forKeyPath: "Email.value_text.email") as! String))
if !MFMailComposeViewController.canSendMail()
{
AppDelegate.sharedInstance().showAlertAction(strTitle: "OK", strMessage: "Mail services are not available") { (success) in
}
return
}
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setToRecipients([strEmail])
composeVC.setSubject("")
composeVC.setMessageBody("", isHTML: false)
self.present(composeVC, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)
{
controller.dismiss(animated: true, completion: nil)
}
これは、 Swift 5 にビューにジェスチャを追加する最も簡単な方法です。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addGestures()
}
// MARK: Add Gestures to target view
func addGestures()
{
// 1. Single Tap or Touch
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGetstureDetected))
tapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGesture)
//2. Double Tap
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapGestureDetected))
doubleTapGesture.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTapGesture)
//3. Swipe
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGetstureDetected))
view.addGestureRecognizer(swipeGesture)
//4. Pinch
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.pinchGetstureDetected))
view.addGestureRecognizer(pinchGesture)
//5. Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGetstureDetected))
view.addGestureRecognizer(longPressGesture)
//6. Pan
let panGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.panGestureDetected))
view.addGestureRecognizer(panGesture)
}
// MARK: Handle Gesture detection
@objc func swipeGetstureDetected() {
print("Swipe Gesture detected!!")
}
@objc func tapGetstureDetected() {
print("Touch/Tap Gesture detected!!")
}
@objc func pinchGetstureDetected() {
print("Pinch Gesture detected!!")
}
@objc func longPressGetstureDetected() {
print("Long Press Gesture detected!!")
}
@objc func doubleTapGestureDetected() {
print("Double Tap Gesture detected!!")
}
@objc func panGestureDetected()
{
print("Pan Gesture detected!!")
}
//MARK: Shake Gesture
override func becomeFirstResponder() -> Bool {
return true
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
if motion == .motionShake
{
print("Shake Gesture Detected")
}
}
}
Swift 5.13つのビューの例
Step:1->ストーリーボードビューを追加し、アウトレットビューを追加
@IBOutlet var firstView: UIView!
@IBOutlet var secondView: UIView!
@IBOutlet var thirdView: UIView!
Step:2-> storyBoardビュータグを追加
Step:3->ジェスチャーを追加
override func viewDidLoad() {
super.viewDidLoad()
firstView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
firstView.isUserInteractionEnabled = true
secondView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
secondView.isUserInteractionEnabled = true
thirdView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
thirdView.isUserInteractionEnabled = true
}
Step:4->ビューを選択
@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
let tag = gestureRecognizer.view?.tag
switch tag! {
case 1 :
print("select first view")
case 2 :
print("select second view")
case 3 :
print("select third view")
default:
print("default")
}
}
MyViewのUITapGestureRecognizerを呼び出す代わりに、handleTap
関数を直接呼び出すことができます。
例:
let tapComments = UITapGestureRecognizer(target: self, action: #selector(goToComments))
labelComments.isUserInteractionEnabled = true
labelComments.addGestureRecognizer(tapComments)
機能:
@objc func goToComments(){
}