Eduardo Ferreira
Eduardo Ferreira

Reputation: 25

How put an image on UIImageView on Swift?

I'm doing a quiz game. But sometimes I want to put a image instead of label question. So, I create:

 @IBOutlet weak var QuestionsLabel = Label!
 @IBOutlet weak var QuestionsImg = UIImageView!

And the rest of code is like that:

func randomQuestions ()
{
    var randomNumber = arc4random_uniform(2)
    while previousNumber == randomNumber
    {
        randomNumber = arc4random_uniform(2)
    }
    previousNumber = randomNumber

    switch(randomNumber)
    {
    case 1:
        QuestionsLabel.text = "O que significa 'estar pisado'?"
        Button1.setTitle("Estar doente", forState: UIControlState.Normal)
        Button2.setTitle("Estar machucado", forState: UIControlState.Normal)
        Button3.setTitle("Estar triste", forState: UIControlState.Normal)
        Button4.setTitle("Estar tonto", forState: UIControlState.Normal)
        correctAnswer = "2"
        break
    case 2:
        hideLabel()
        QuestionsImg.image = UIImage(named: "arante3")
        Button1.setTitle("Lagoinha", forState: UIControlState.Normal)
        Button2.setTitle("Canasvieiras", forState: UIControlState.Normal)
        Button3.setTitle("Armação", forState: UIControlState.Normal)
        Button4.setTitle("Santinho", forState: UIControlState.Normal)
        correctAnswer = "3"
        break
    default:
        break
    }
}

and the func hideLabel is like that:

func hideLabel()
    {
        QuestionsLabel.hidden = true
    }
    func unhideLabel()
    {
        QuestionsLabel.hidden = false
    }

But not work! What is the problem?

Upvotes: 0

Views: 331

Answers (1)

Duncan C
Duncan C

Reputation: 131426

"But not work". That is extremely not helpful. Ok, what does that mean? Does the text always stay visible and the image too? does the image appear and disappear but the label doesn't go away? Does your phone burst into flames?

Your code has a number of problems. First of all, arc4random_uniform(2) creates values of 0 or 1. Your cases should be 0 and 1, not 1 and 2.

You need case 0 (show label) to call unhideLabel and hide the image view.

You need case 1 (hide label, show image) to call hideLabel and show the image view. by setting QuestionsImg.hidden = false

As an aside, variable names should start with a lower-case letter. Only types and class names should start with an upper-case letter. That is a strong naming convention in Swift.

Upvotes: 3

Related Questions