【问题标题】:SwiftUI - How to change properties on an Image view that's stored inside a static list?SwiftUI - 如何更改存储在静态列表中的图像视图的属性?
【发布时间】:2020-10-23 15:27:34
【问题描述】:

我有一个存储在类的静态变量中的 SwiftUI 图像视图列表。我需要在显示图像时更改图像的一些属性。虽然属性不会自动完成。我也有一些属性在我添加它们时不起作用。这是我的代码:

import SwiftUI

extension Image: Identifiable {
    public var id: UUID {
        return UUID()
    }
}

class ImageClass: Identifiable {
    static var imageList = [Image(systemName: "circle"), Image(systemName: "circle.fill")]
}

struct ContentView: View {
    var body: some View {
        ForEach(ImageClass.imageList, id: \.id) { image in
            image.foregroundColor(.red) // autocomplete doesn't work, sometimes properties don't work
        }
    }
}

为什么会这样?谢谢!

【问题讨论】:

  • 什么不工作?
  • 使用 Xcode 12 一切正常。

标签: arrays image properties swiftui static-variables


【解决方案1】:

您不应将使用 View 存储为 static 变量。 (因为他们可以永远活在记忆中)。相反,您可能想使用enum

enum ImageName: String, CaseIterable, Identifiable {
    var id: ImageName { self } // could be any other id you need

    case circle
    case circleFill = "circle.fill"

    var image: Image { Image(systemName: self.rawValue) }
}

struct ContentView: View {
    var body: some View {
        HStack {
            ForEach(ImageName.allCases) {
                $0.image.foregroundColor(.red) // Auto complete works like a charm
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多