Search code examples
iosswiftgesture

iOS / Swift Can't add gesture to child class


I'm writing an child class but couldn't add gesture recognize for it. Selector error. Here is my code:

import UIKit

class Alert: KeyboardViewController {

    var AlertContainer = UIView()

    func ShowAlert(message: String,view: UIView)
    {
        var tap = UITapGestureRecognizer(target: self, action:Selector("CloseAlertView"))
        tap.numberOfTapsRequired = 1
        AlertContainer.addGestureRecognizer(tap)

        AlertContainer.setTranslatesAutoresizingMaskIntoConstraints(false)
        AlertContainer.userInteractionEnabled = true
        AlertContainer.backgroundColor = UIColor(rgb: 0x000000, alpha: 0.8)
        view.addSubview(AlertContainer)



var CTop = NSLayoutConstraint(item: AlertContainer, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0)
        var CRight = NSLayoutConstraint(item: AlertContainer, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1.0, constant: 0.0)
        var CLeft = NSLayoutConstraint(item: AlertContainer, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0.0)
        var CBottom = NSLayoutConstraint(item: AlertContainer, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
        view.addConstraints([CTop,CRight,CLeft,CBottom])
    }

    func CloseAlertView() {
        AlertContainer.removeFromSuperview()
    }
}

But when i tap on to this view, error: exc_bad_access or some time unrecognized selector sent to instance. Really don't know why ? and one more question that i can't access to parent class view by super.view ?


Solution

  • Are you are calling this class in the following way (if not ignore my answer)?

    // wrong implementation
    func myFunc() {
        var a = Alert()
        a.ShowAlert("Message", view: view)
    }
    

    The previous code is wrong (and causes BAD_ACCESS) because a does not exists anymore after the function finished. So when the gesture is fired, it acts on nothing and crashes. Solution:

    var a = Alert()  // a property of the caller class
    
    func myFunc() {
        a.ShowAlert("Message", view: view)
    }
    

    In this way the life of a is long enough to wait for the gesture.