ios - 当单词出现在数组标签中时设置图像

标签 ios swift uiimage uilabel

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

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

这是数组:

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

这是随机标签文本:“

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

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

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

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

最佳答案

如何使用一个but变量和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()!)"

关于ios - 当单词出现在数组标签中时设置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54263887/

相关文章:

ios - 如何全屏显示图像并通过类似于 Apple Photos 的滑动关闭

ios - UISegmentedControl 获取之前选择的索引

php - gcm推送通知: first success,然后未在IOS中注册

ios - 如何在通过共享扩展选择的 NSUserDefaults 中存储多个图像

ios - 从 PDFDocument iOS 获取页面大小

ios - 将 UIView 渲染为没有 subview 的图像

iOS 随机数的高斯分布

swift - 如何为具有给定前缀的 URL 提供文件?

ios - Swift:删除层,而不删除 UITableViewCell 中的 UIView

iphone - 从 Amazon Web Services S3 加载的图像像脉冲一样无限滚动