无法在UITapGestureRecognizer上执行函数

时间:2017-02-01 11:16:54

标签: iphone swift

每当我触摸屏幕时都没有任何反应。看起来像handleDismiss()函数永远不会被触发。有谁知道这里真正的问题是什么。

import UIKit

class SettingLauncher : NSObject{

    let blackView = UIView();

    func showSettingMenu(){
        if let window = UIApplication.shared.keyWindow{

            blackView.backgroundColor = UIColor(white: 0, alpha: 0.5);
            blackView.isUserInteractionEnabled = true;
            blackView.addGestureRecognizer(UITapGestureRecognizer(target: nil, action: #selector(self.handleDismiss)));

            window.addSubview(blackView);
            blackView.frame = window.frame;
            blackView.alpha = 0.1;

            UIView.animate(withDuration: 0.5) {
                self.blackView.alpha = 0.5;
            }
        }
    }

    func handleDismiss(){
        print("Touch recognised");
    }
}

2 个答案:

答案 0 :(得分:0)

你必须告诉blackView.addGestureRecognizer(UITapGestureRecognizer(target: nil, action: #selector(self.handleDismiss))); 哪个类将处理响应 - 不仅仅是哪个函数,而是哪个类

更改

blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleDismiss)))

class ViewController: UIViewController
{
    let blackView = UIView()

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    func handleDismiss(){
        print("Touch recognised");
    }

    @IBAction func cmdDoOtherStuff(_ sender: Any)
    {
        if let window = UIApplication.shared.keyWindow{

            blackView.backgroundColor = UIColor(red: 1.0, green: 0, blue: 0, alpha: 0.5)//(r: 0, alpha: 0.5)
            blackView.isUserInteractionEnabled = true
            blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.handleDismiss)))

            window.addSubview(blackView)
            blackView.frame = window.frame
            blackView.alpha = 0.1
             UIView.animate(withDuration: 0.5) {
             self.blackView.alpha = 0.5;
             }
        }
    }
}

这是我工作的一个例子。我从一个按钮启动视图 - 我不知道你是如何启动的,但这不应该重要

var modalInstance = $modal.open({
animation: true,
templateUrl: 'myPopup.html',
controller: 'MyController',
scope: $scope   

答案 1 :(得分:0)

我收到了上述错误,因为我通过另一个类函数调用了函数showSettingMenu(),如下所示: -

func handleMoreSetting(){
        let settingLauncher = SettingLauncher();
        settingLauncher.showSettingMenu();  // Call SettingLauncher class
    }

当我将settingLauncher声明为全局实例时,问题就消失了。

let settingLauncher = SettingLauncher();
func handleMoreSetting(){
        settingLauncher.showSettingMenu();  // Call SettingLauncher class
    }

有人知道问题发生的原因吗?在这两种情况下,我调用相同的函数但结果不同。