Hanushka Suren
Hanushka Suren

Reputation: 793

Button click event (UIButton TouchUpInside action) not working - IOS/Swift

In my application's storyboard there is a UIViewController(child) which loads inside another UIViewController(parent).

This is the code I used inside the parent view controller to load the child view controller over all the subviews in parent view controller including navigation bar.

let window: UIView? = UIApplication.sharedApplication().keyWindow;

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil);
let viewController: UIViewController = storyboard.instantiateViewControllerWithIdentifier("CPBackConfirmMessageUIView");

window?.addSubview(viewController.view); 

This is how they look in my storyboard

enter image description here

This is how it looks after child view controller is loaded in side parent view

enter image description here

Inside the child view controller there are two buttons as you can see.I have added (TouchUpInside) actions to those buttons inside child view's controller class and it is not working. But ViewDidLoad methods is working fine(I added some animations and they are working).

Can someone tell me how can I write actions to those buttons and get them work or let me know if I am doing any thing wrong here. Any help would be highly appreciated.

Edit: This is how I wrote my IBAction

@IBAction func abc(sender: AnyObject) {    
    print("Worked");
}

Upvotes: 1

Views: 7869

Answers (1)

Vladimir K
Vladimir K

Reputation: 1382

Try to use child viewController as a property. In current implementation viewController object should be released as soon as method completes. Property will make sure that viewController object will be alive when you press a button.

So instead of:

let viewController: UIViewController = storyboard.instantiateViewControllerWithIdentifier("CPBackConfirmMessageUIView");

Try this:

class YourParentViewController: UIViewController {

    var viewController: UIViewController!

 func someMethod() {
    let window: UIView? = UIApplication.sharedApplication().keyWindow;

    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil);
    viewController = storyboard.instantiateViewControllerWithIdentifier("CPBackConfirmMessageUIView");

    window?.addSubview(viewController.view); 
 }

}

Upvotes: 9

Related Questions