如何隐藏几个按钮是按钮数组?

Mik*_*lin 1 uibutton ios swift

如何在按钮数组中隐藏多个按钮?我需要这样做:如果问题的数量少于按钮数组,那么应该隐藏具有附加功能的按钮。

@IBOutlet var firstButton: UIButton!
@IBOutlet var secondButton: UIButton!
@IBOutlet var thirdButton: UIButton!
@IBOutlet var fourthButton: UIButton!
@IBOutlet var fifthButton: UIButton!
@IBOutlet var sixthButton: UIButton!

    func generateQuestions() -> Question {
        // MARK: - Questions
        let questionOne = Question.init("questionOne?")
        let questionTwo = Question.init("questionTwo")

        // MARK: - Answers
        let answerOne = Answer.init("answerOne", type: .python, nextQuestion: nil)
        let answerTwo = Answer.init("answerTwo", type: .next, nextQuestion: questionTwo)
        let answerThree = Answer.init("answerThree", type: .next, nextQuestion: nil)
        let answerFour = Answer.init("answerFour", type: .next, nextQuestion: nil)
        let asnwerFive = Answer.init("asnwerFive", type: .next, nextQuestion: nil)
        let answerSix = Answer.init("answerSix", type: .next, nextQuestion: nil)

        let answerOneQT = Answer.init("answerOneQT", type: .next, nextQuestion: nil)
        let answerTwoQT = Answer.init("answerTwoQT", type: .next, nextQuestion: nil)

        // MARK: - Put answers to question
        questionOne.answers = [answerOne, answerTwo, answerThree, answerFour, asnwerFive, answerSix]
        questionTwo.answers = [answerOneQT, answerTwoQT]
        return questionOne
    }

//MARK: - Update label and titles of Buttons
    func updateTittles(_ question: Question?) {
       let arrayOfButton = [firstButton, secondButton, thirdButton, fourthButton, fifthButton, sixthButton]
        questionLabel.text = question?.text
        firstButton.setTitle(question?.answers[0].text, for: .normal)
        secondButton.setTitle(question?.answers[1].text, for: .normal)
        thirdButton.setTitle(question?.answers[2].text, for: .normal)
        fourthButton.setTitle(question?.answers[3].text, for: .normal)
        fifthButton.setTitle(question?.answers[4].text, for: .normal)
        sixthButton.setTitle(question?.answers[5].text, for: .normal)
    }

}
Run Code Online (Sandbox Code Playgroud)

Raz*_*ana 5

首先,我建议使用IBOutletCollection 之类的

@IBOutlet var buttons: [UIButton]!
Run Code Online (Sandbox Code Playgroud)

其次隐藏所有你的按钮

func hideAllbuttons() {

     for button in self.buttons {
         button.isHidden = true
     }
}
Run Code Online (Sandbox Code Playgroud)

那么updateTittles就会变成

func updateTittles(_ question: Question?) {
     hideAllbuttons()

     for index in 0..<question.answers.count {

         if index < self.buttons.count {
            self.buttons[index].isHidden = false
            self.buttons[index].setTitle(question?.answers[index].text, for: .normal)
         }
     }

}
Run Code Online (Sandbox Code Playgroud)