0





20

Advertisement

Whenever i touch on the screen nothing happens. looks like handleDismiss() function is never fired. Does anybody knows what is the real problem here.

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");
    }
}
Question author Bikram | Source

Advertisement


0


You have to tell the UITapGestureRecognizer which class will be handling the response - not just which function, but which class

Change

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

To

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

Here's an example which I have working. I am initiating the view from a button - I don't know how yours is started, but that shouldn't matter

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;
             }
        }
    }
}
Answer author Russell