Rujoota Shah
Rujoota Shah

Reputation: 1321

Custom uiview with button inside alertController does not work in iOS

I am trying to create an alert controller which has a custom view inside it. The custom view is loaded from xib file. The custom view contains a uiswitch. The problem is that its click event is not being triggered and from UI switch is not turned on/off on click. Here is the code I am trying to work on:

This is the button click event of my view controller to present alert:

@IBAction func btnClicked(_ sender: UIButton) {
        let alertController = UIAlertController(title: "\n\n\n\n\n\n", message: "", preferredStyle: UIAlertControllerStyle.alert)
        let customView=Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)!.first! as! CustomView
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {(alert: UIAlertAction!) in print("cancel")})
        alertController.addAction(cancelAction)
        let somethingAction = UIAlertAction(title: "Something", style: .default, handler: {(alert: UIAlertAction!) in print("something")})
        alertController.addAction(somethingAction)

        alertController.view.addSubview(customView)
        self.present(alertController, animated: true, completion:{})
    }

This is the code inside CustomView class:

class CustomView: UIView {
    @IBAction func switchClicked(_ sender: UISwitch) {
        print("switch cliked")
    }
}

My CustomView.xib file has the referencing layout properly set. It just has one uiswitch. The CustomView.xib has its size set to 'freeform'(not sure if it matters). I also tried setting isUserInteractionEnabled to false or true at various places for CustomView and/or alertController.view after searching for similar issues but nothing works.

Upvotes: 0

Views: 691

Answers (2)

Jitendra Tanwar
Jitendra Tanwar

Reputation: 249

I think xib view will triger method only when same class has been loaded in memory. In your case this might be an issue . To test this u can add custom view in same class in which u are showing alert .

Upvotes: 0

rollingcodes
rollingcodes

Reputation: 16008

You should be capturing the valueChanged control event but if you want to do the value change programmatically via click I suppose you could do:

class CustomView: UIView {
    @IBAction func switchClicked(_ sender: UISwitch) {
        sender.setOn(!sender.isOn, animated: true)
    }
 }

Upvotes: 1

Related Questions