You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SwiftUI中通过UIImage为SF Symbol设置指定色调

让黑色背景VStack中的SF Symbol显示指定色调(基于UIImage设置)

要实现这个需求,核心是直接对UIImage做颜色与渲染模式的配置:

  • 调用UIImage的withTintColor(_:renderingMode:)方法,传入目标色调,同时将渲染模式设置为.alwaysTemplate
  • 模板模式下,SF Symbol会仅保留形状轮廓,填充你指定的色调,在黑色背景上能清晰呈现目标颜色

完整实现代码

struct ContentView: View {
    var body: some View {
        VStack {
            createHelloWorldView(image: UIImage(systemName: "airplane.circle.fill")!.withTintColor(.white, renderingMode: .alwaysTemplate), hello: "Hello", world: "World")
        }
        .background {
            Color.black.ignoresSafeArea()
        }
    }
    
    @ViewBuilder
    func createHelloWorldView(image: UIImage, hello: String, world: String) -> some View {
        Image(uiImage: image)
            .resizable()
            .scaledToFit()
            .frame(width: 150, height: 150)
        
        Text(hello)
            .font(.title)
        
        Text(world)
            .font(.title2)
    }
}

开发注意事项

实际项目中建议对UIImage(systemName:)的返回值做可选绑定处理,避免因符号名称错误导致崩溃,示例如下:

if let symbolImage = UIImage(systemName: "airplane.circle.fill")?.withTintColor(.white, renderingMode: .alwaysTemplate) {
    createHelloWorldView(image: symbolImage, hello: "Hello", world: "World")
}

内容的提问来源于stack exchange,提问作者batman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 18:22:10