简体   繁体   中英

addTarget is not getting called on UIButton in swift

I am trying to make a tooltip box programatically. For that what I am trying to do is create a container view ("Tooltip class") which is equal to size of its parent view, inside that container view I am adding a tooltip view. Inside that I am adding a UIButton for which I am adding a target. My code snippet:

let container: UIView = UIView()
let tooltipView: UIView = UIView()
var closeButton: UIButton = UIButton()

container.frame = view.frame
container.center = view.center
container.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.6)

tooltipView.frame = CGRectMake(40, 40, container.frame.size.width - 80, container.frame.size.height - 80)
tooltipView.backgroundColor = UIColor.whiteColor()
tooltipView.layer.cornerRadius = 10.0

Adding button:

closeButton = UIButton(type: .Custom)
closeButton.imageView?.contentMode = .ScaleAspectFit
closeButton.frame = CGRectMake(tooltipView.frame.size.width - 45, 0, 45, 45)
closeButton.setBackgroundImage(UIImage(named: "close.png"), forState: .Normal)
closeButton.addTarget(self, action: "closeTooltip", forControlEvents: UIControlEvents.TouchUpInside)

Function:

func closeTooltip() {
    print("action")
    // container.removeFromSuperview()
}

I have implemented the code in a method in a separate file and I am calling this create tooltip method from main viewcontroller class. I have tried multiple solutions, like, add "userInteractionEnabled = true" but it didn't worked.

Since I am calling this entire tooltip method inside other class ("ViewController") I thought, since I am passing self to it and the target mentioned in tooltip class might be the issue. So added same method in "ViewController" class just to test. But that too didn't work.

Please give me some advice where I am missing here.

Thanks

hmm, its hard to guess from what you show, but I think the problem is, that you create a new UIButton object before adding the target and don't add it to the view . So basically I think you add the button to the view on creating the container but then you add target to a button that you don't use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM