0

I am working an app with quizzes, have 4 UIButtons (custom type) on subview which is custom view and none of the buttons is recognising the action even though I set the target. I have to do it programatically.

I have tried setting isUserInteractionEnabled but it is not working. Buttons are on the view, respecting the bounds.

Here, viewDidLoad from InitialViewController:

override func viewDidLoad() 

{

    super.viewDidLoad()

    self.questionView?.firstanswer!.isEnabled = true

    self.questionView?.firstanswer!.addTarget(self, action: #selector(self.answerTheQuestion), for: UIControl.Event.touchUpInside)

    self.questionView?.secondanswer!.addTarget(self, action: #selector(self.answerTheQuestion), for: UIControl.Event.touchUpInside)

    self.questionView?.thirdanswer!.addTarget(self, action: #selector(self.answerTheQuestion), for: UIControl.Event.touchUpInside)

    self.questionView?.fourthanswer!.addTarget(self, action: #selector(self.answerTheQuestion), for: UIControl.Event.touchUpInside)

}

Here is the action function:

@objc func answerTheQuestion(_sender:UIButton) {

   print("aa")

   if let questionsAnswers = self.quizzes?.quizzes[self.randomNumber!]["questions"] as?  [[String:Any]] {

    if (questionsAnswers[self.randomQuestion!]["question"] as? String) != nil { 

       if let correctAnswer = questionsAnswers[self.randomQuestion!]["correct_answer"] as? String {
           if _sender.titleLabel?.text == correctAnswer {
              _sender.backgroundColor = UIColor.green
           } else {
            _sender.backgroundColor = UIColor.red
           }
       }
    }
  } 
}

View and buttons are added normally, only tap is not working.

It should go red when the answer is wrong, and green when it is right. Questions and everything else is added normally, but it even won't print "aaa" in the beginning of the target function. Pls help, thanks!!

Razi Tiwana
  • 1,425
  • 2
  • 13
  • 16
D.J.
  • 1
  • Can we have a screenshot of the debug view hierarchy? – Fallah Apr 09 '19 at 22:25
  • Is `questionView` nil during `viewDidLoad()`? – Don Apr 10 '19 at 01:39
  • @Don No it is not. It normally looks on the screen with buttons and labels and everything – D.J. Apr 10 '19 at 04:08
  • @Fallah There is InitialViewController with subview QuestionView (which is custom view) and UIButtons which are subviews of questionview. – D.J. Apr 10 '19 at 07:48
  • Is userInteractionEnabled true for questionView? – Roux Apr 10 '19 at 09:02
  • Also, if your function is `func answerTheQuestion(_ sender: UIButton)`, your #selector should be `#selector(answerTheQuestion(_:))`. If it is `func answerTheQuestion(sender: UIButton)` it should be `#selector(answerTheQuestion(sender:))` – Roux Apr 10 '19 at 09:20
  • If you have not found a solution please attach the .xcodeproj – Fallah Apr 15 '19 at 13:29

0 Answers0