我有这个枚举:
enum WeatherMapDisplayType {
case temperature
case wind
}
我可以这样声明一个变量吗?
let markerView: mode == .temperature ? WeatherMapItemTemp : WeatherMapItemWind = UIView.fromNib()
知道mode
的类型为WeatherMapDisplayType
如何以一种优雅的方式处理这种情况?
编辑:
我希望能够做这样的事情:
let markerView: WeatherMapItem = UIView.fromNib()
markerView.frame = CGRect(x: 0, y: 0, width: 80, height: 30)
markerView.setupWeatherInformations(mode: self.currentDisplayMode, forecast: forecasts)
marker.iconView = markerView
以前我只有WeatherMapItem
类型。
然后我被要求添加其他天气地图项目,这就是为什么我现在拥有WeatherMapItemTemp
和WeatherMapItemWind
(也对应于我的枚举显示类型)的原因。
func setupWeatherInformations(forecast: Forecast.HourlyForecast)
这是我的自定义类中的一种方法,用于配置出口。
但是,如果我从框架中初始化自定义视图,则无法访问此方法,因为它是UIView类型的。
答案 0 :(得分:1)
更新后的答案
如果要在单个三元语句中设置数据,请在自定义视图类中声明一个函数。 像这样
class WeatherMapItemTemp: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func setForecast(forecastData: Forecast) -> WeatherMapItemTemp {
let view = WeatherMapItemTemp.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100))
//Set your appropriate value to your view objects
return view
}
}
使用此方法
let markerView = mode == .temperature ? (WeatherMapItemTemp().setForecast(forecastData: YOUR_FORECAST_OBJ)) : (WeatherMapItemWind().setForecast(forecastData: YOUR_FORECAST_OBJ))
更新2
是的,您需要从笔尖中加载
如下更新setForecast。
class func setForecast(forecastData: Forecast) -> WeatherMapItemTemp {
let view = UINib(nibName: "WeatherMapItemTemp", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! WeatherMapItemTemp
//Do your further stuff here
return view
}
答案 1 :(得分:1)
向这些视图添加通用协议:
protocol WeatherMapItem where Self: UIView {
func setupWeatherInformations()
}
class WeatherMapItemTemp: UIView, WeatherMapItem {
func setupWeatherInformations() {
// setup
}
}
class WeatherMapItemWind: UIView, WeatherMapItem {
func setupWeatherInformations() {
// setup
}
}
将计算变量添加到枚举:
enum WeatherMapDisplayType {
case temperature
case wind
var view: (UIView & WeatherMapItem)? {
var nibName: String? = nil
switch self {
case .temperature:
nibName = "WeatherMapItemTemp"
case .wind:
nibName = "WeatherMapItemWind"
}
if let nibName = nibName, let views = Bundle.main.loadNibNamed(nibName, owner: nil), views.count > 0 {
return views[0] as? UIView & WeatherMapItem
}
return nil
}
}
现在您可以生成如下视图:
// assuming mode is the variable of type WeatherMapDisplayType
let view = mode.view
view?.setupWeatherInformations()
return view