Word出现在数组标签中时设置图像

时间:2019-01-19 03:43:53

标签: ios swift uiimage uilabel

当标签显示随机数组中的某个单词时,我试图将图像视图设置为特定图像。

当特定单词是数组中标签的文本时,应该将图片设置为图像视图。

这是数组:

    let freeMoodArray = ["Happy", "Sad", "Angry", "Annoyed", "Curious", "Bored", "Chilled", "Furious", "Excited", "Scared", "Emotionless", "Shocked", "Tired", "Sick", "Amused"]

这是随机标签文本:“

self.moodAnswer.text = "\(self.freeMoodArray.randomElement()!)"

现在,当我加载视图时,图像从正在工作的数组中选择一个随机单词。现在,假设它说Happy作为标签的文本。 我只想说快乐就设置一个特定的图像。

这是我的代码,它不起作用:(此函子在viewDidLoad()中被调用)

    func emojiMood() {
    if moodAnswer.text == "Happy" {
        emojiImg.image = UIImage(named: "happy.png")
    }
}

1 个答案:

答案 0 :(得分:0)

一个变量和DidSet如何?

// create a variable
var moodAnswer :  string = "" {
   didSet {
       // if or switchCase, set image only if the text is equal to Happy
       if moodAnswer == "Happy" {
          emojiImg.image = UIImage(named: "happy.png")
       }
       // always set text field with new updated text
       self.moodAnswerLabel.text = moodAnswer
   }
}

// in your code always set moodAnswer variable, this is more clean and also you set label and image only in a single place
self.moodAnswer = "\(self.freeMoodArray.randomElement()!)"