mercredi 30 janvier 2019

How to hide uibutton if its title text is empty or unassigned?

The code and question represents an Xcode project in Swift. I have a a group of buttons that display options according to which text is presented on a label. The label text is derived from the keys of a dictionary and the button texts are derived from the values of that same dictionary. The dictionary type is [String: [String]. The keys and values are both placed in arrays. I currently display the correct data but some values differ in length than others. For example one key has 3 values and another key has 5. I want to hide the buttons if there is not text to send to it. So if a key is presented in a label and has 3 values I only want to display 3 buttons and so. What would be the best way to achieve this functionality? Here is my code:

    func startSurvey() {

    if surveyQuestions.isEmpty {
        surveyQuestions = Array(SampleSurvey().surveyquestions.keys)
        print(surveyQuestions)
    }

    let rand = Int(arc4random_uniform(UInt32(surveyQuestions.count)))
    questionTitle.text = surveyQuestions[rand]

    var choices = SampleSurvey().surveyquestions[surveyQuestions[rand]]!
    print(choices)
    print(choices.count)
    surveyQuestions.remove(at: rand)

    var button = UIButton()
    var x = 0
 // var choicePool = choices.count

    if choices.count == 2 {
        for index in 1...2 {
            button = view.viewWithTag(index) as! UIButton
            button.setTitle(choices[x], for: .normal)
            x += 1
            if button.titleLabel?.text == nil {
                button.isHidden = true
            }
        }
    }

    else if choices.count == 4 {
    for index in 1...4 {
        button = view.viewWithTag(index) as! UIButton
        button.setTitle(choices[x], for: .normal)
        x += 1

        if button.titleLabel == nil {
            button.isHidden = true
        }

        }
    }

Here is a screenshot of the simulator, as you can see this particular key has only 2 values so there are 3 blank buttons, I want to hide the buttons that are blank:

enter image description here

Aucun commentaire:

Enregistrer un commentaire