Dog*_*bas 6 swift swiftui xcode15
我的 SwiftUI 项目中有一个 Swift 包,其中包含 UI 组件的样式。此外,此包还包括一个资源文件夹,其中包含可在样式中使用的资源。我可以通过名称获取图像,但我想知道是否可以使用枚举访问图像。因为 Xcode 15 会自动生成资产符号。
\n下面的例子可以解释我的意思:
\npublic struct CheckboxToggleStyle: ToggleStyle {\n@Binding var color: Color\n\nlet checked = Image("checkbox-checked", bundle: .module) // \xe2\x9c\x85 works\nlet unchecked = Image("checkbox-unchecked", bundle: .module) // \xe2\x9c\x85 works\nlet checked = Image(.checkboxChecked) // \xe2\x9d\x8c failed\nlet unchecked = Image(.checkboxUnchecked) // \xe2\x9d\x8c failed\n\npublic func makeBody(configuration: Configuration) -> some View {\n (configuration.isOn ? checked : unchecked)\n .renderingMode(.template)\n .foregroundColor(color)\n .onTapGesture {\n withAnimation {\n configuration.isOn.toggle()\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n}
\nxTw*_*eDx -3
我是这样做的。如果您想了解更多详细信息,请随时查看我的包:Iconoirhttps ://github.com/iconoir-icons/iconoir-swift/tree/main
最终,您需要定义一个任何名称的枚举,然后将所有相应的字符串分配给Symbol Names该枚举,然后使用实用程序方法或枚举计算属性。理论上,您还可以编写一个脚本来自动获取所有符号名称并为您生成枚举,这就是我最终所做的,Iconoir因为我无法手动输入 1000 多个枚举声明。
public enum Iconoir: String, CaseIterable {
case bell = "bell"
Run Code Online (Sandbox Code Playgroud)
@available(iOS 13, macOS 10.15, *)
public extension Iconoir {
/// Returns a SwiftUI Image of the Iconoir icon.
var asImage: Image {
return Image(self.rawValue, bundle: Bundle.module)
.renderingMode(.template)
}
/// Returns an image, from the Iconoir bundle, if there is a matching key.
/// - Parameter string: key that matches iconoir icon.
/// - Returns: SwiftUI Image
static func image(from string: String) -> Image {
return Image(string, bundle: Bundle.module)
.renderingMode(.template)
}
}
#endif
Run Code Online (Sandbox Code Playgroud)
Iconoir.bell.asImage
Iconoir.bell.asUIImage
Iconoir.image(from: "bell")
Run Code Online (Sandbox Code Playgroud)
如果您没有太多图像,则可以简单地将执行类似操作的计算属性添加到您的枚举中,而不是像我所做的那样创建扩展。
var image: Image {
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1569 次 |
| 最近记录: |