Swift使用枚举对象值来有条件地设置UIImageView.image

时间:2018-08-28 04:34:14

标签: swift enums

我想使用一个枚举,该枚举有10种情况,应对应10种不同的天气情况。如果对象的字符串值与枚举之一匹配,则将v17.0.1设置为适当的值。一些字符串键也用短划线隔开。

最有效的方法是什么?

2 个答案:

答案 0 :(得分:2)

我会这样的

enum Weather: String {
    case temperature
    case atmosphericPressure = "atmospheric_pressure"
    case wind

    var image: UIImage? {
        return UIImage(named: rawValue)
    }
}

答案 1 :(得分:1)

您可以通过这种方式实现

enum Weather : String {
    case  temperature, atmospheric_pressure, wind, humidity, precipitation,cloudiness
    func displayImage()->String {
        switch self {
        case .temperature:
            return "temperature.png"
        case .atmospheric_pressure:
            return "atmospheric_pressure.png"
        case .wind:
            return "wind.png"
        case .humidity:
            return "humidity.png"
        case .precipitation:
            return "precipitation.png"
        case .cloudiness:
            return "cloudiness.png"
        }
    }
}

class ViewController: UIViewController {
    @IBOutlet weak var ibOutletButton: UIButton!
    var weather = Weather.temperature
    @IBOutlet weak var imageView : UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
         imageView.image = UIImage(imageLiteralResourceName: weather.displayImage())
    }
}