Swift 3 - 在代码中访问嵌套子视图属性

Swift 3 - Access nested subviews properties in code

为了纯粹的培训,我正在开发一个天气应用程序编码整个 UI 而不是使用故事板。

我有一个嵌套的视图结构如下:

SuperView --> UIView(有 5 个 UIView 类型的子视图)。 5 个 UIView 中的每一个包含:1 个 UIImageView,2 个 UILabels

现在,当我调用我的委托函数来检索天气时,我无法使用天气图标、天气描述、日期更新这些值。

我尝试为每个子视图使用标签,但没有成功。

给大家看点:

这是我检索预测数据(图标、描述、日期)的地方:

//MARK: Forecast Wheel elements
let forecastWeatherWheel = UIView()
var forecastDays = [String]()
var forecastDescriptions = [String]()
var forecastIcons = [String]()


func setForecastWeather(forecast: ForecastWeatherData) {

    forecastDays = forecast.forecastDay
    forecastDescriptions = forecast.weatherDescription
    forecastIcons = forecast.icon

    for (index,forecastContainerView) in (forecastWeatherWheel.subviews.filter{[=11=] is UIView}).enumerated(){
        for (index,iconImageView) in (forecastContainerView.subviews.filter{[=11=] is UIImageView}).enumerated(){
            let iconImage = iconImageView as! UIImageView
            iconImage.image = UIImage(imageLiteralResourceName: forecastIcons[index])
        }
    }
}

有了它的嵌套,我已经 - 以某种方式 - 能够访问我的嵌套视图的图像 属性,而不是循环遍历图标数组,它在所有 5 个子视图中始终使用相同的图标...

非常感谢任何帮助,因为我已经为此苦苦挣扎了 12 个多小时:|

真正的答案当然是使用视图子类,带有图像视图和每个标签的访问器,而不是像这样使用子视图层次结构。但是你现在所做的事情有什么问题:

for (index,forecastContainerView) in (forecastWeatherWheel.subviews.filter{[=10=] is UIView}).enumerated(){

这里的过滤没有意义; subviews 中的所有内容都是 UIView。您将获得 5 次通过这里。

        for (index,iconImageView) in (forecastContainerView.subviews.filter{[=11=] is UIImageView}).enumerated(){

您在此处的过滤器仅用于 return 单个视图 - 图像视图,因为其他视图不是图像视图。这意味着这个循环只会执行一次。

            let iconImage = iconImageView as! UIImageView
            iconImage.image = UIImage(imageLiteralResourceName: forecastIcons[index])

这意味着 index 这里是您的 inner 索引,它始终为 0。

要么为每个索引变量使用不同的名称,要么这样写(未经测试,在浏览器中输入):

for (index, forecastContainerView) in forecastWeatherWheel.subviews.enumerated() {
    let imageView = forecastContainerView.subviews.first(where: { [=13=] is UIImageView } ) as! UIImageView
    imageView.image = UIImage(imageLiteralResourceName: forecastIcons[index]
}