SwiftUI Tips:在 ViewBuilder 中方便的打印调试信息

我们在调试 SwiftUI View 的时候有时需要在打印一些内容。最常见的打印方式是使用print:

swift 复制代码
struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .foregroundStyle(.tint)
            let _ = print("my log")
            Text("Hello, world!")
        }
        .padding()
    }
}

但是如果想要打印某个 View 节点的信息(类型、属性)就有点不方便了。

假设我有一个自定义的控件,MyText,有一个公开的属性 title:

swift 复制代码
struct MyText: View {
    let title: String
    
    var body: some View {
        Text(title)
            .foregroundColor(.red)
    }
}

要如何调试打印这个 MyText 的title 呢?这个时候直接使用 print 就不好用了。硬来的话只能多复制一个 MyText 了:

swift 复制代码
struct PrintView: View {
    var body: some View {
        VStack {
            MyText(title: "我的内容")
            let _ = print("mylog:\(MyText(title: "我的内容").title)")
        }
        .padding()
    }
}

可以通过自定义一个泛型打印函数来解决这个问题:

swift 复制代码
func printThrough<T>(
    _ t: T, 
    _ message: String? = nil, 
    map: ((T) -> String)? = nil
) -> T {
    let description = if let map {
        map(t)
    } else {
        String(describing: t)
    }

    let message = if let message {
        "\(message): '\(description)'"
    } else {
        description
    }

    print(message)

    return t
}

printThrough 第一个参数接收任意内容(view)。第二个参数可空接收要打印的字符串前缀,如果没有传入默认打印第一个参数的类型信息。第三个参数是个闭包,在闭包中可以获得第一个参数的实例,用于打印自定义的实例信息。

有了这个函数以后我们前面的需求就可以优雅地实现了:

swift 复制代码
struct ContentView: View {
    var body: some View {
        VStack {
            printThrough(
                Text("Hello, world!")
            )
            printThrough(
                MyText(title: "我的内容"),
                "MyLog",
                map: { "内容是:\($0.title)"})
        }
        .padding()
    }
}

控制台就会输出这样的结果:


相关推荐
东坡肘子5 天前
谁是 AI-relay App 的真正威胁 -- 肘子的 Swift 周报 #158
人工智能·swiftui·swift
东坡肘子12 天前
当 Build in Public 重新转入地下 -- 肘子的 Swift 周报 #157
人工智能·swiftui·swift
OliverQiu13 天前
开源一个 macOS 小工具:集中管理 ChatGPT 的网络启动配置
macos·chatgpt·swiftui·mac·proxy·codex·dmg
传奇开心果编程16 天前
【SwiftUI提高练中学】第9课 安全与隐私
swiftui·移动开发·swift·编程语言理论·开发范式·编程框架·声明式ui
传奇开心果编程17 天前
【声明式UI开发实用技术学与练】第8课 状态提升与下放
学习·flutter·react native·ui·swiftui·composer
东坡肘子17 天前
Swift Server,又多了一个 Google -- 肘子的 Swift 周报 #156
人工智能·swiftui·swift
传奇开心果编程18 天前
【现代声明式UI学与练】第4课 列表渲染与 key——如何高效渲染列表、key 的作用、列表重排时的状态保持
学习·flutter·react native·ui·swiftui·android jetpack
传奇开心果编程18 天前
【SwiftUI提高练中学】第8课 网络层架构:拦截器、重试、缓存与离线优先
学习·macos·ui·ios·swiftui
传奇开心果编程18 天前
【现代声明式UI学与练】第7课 组件通信——父传子、子传父、跨层级通信、状态提升与 Context
学习·flutter·react native·ui·swiftui·android jetpack
tink19 天前
告别 Xcode IDE:用 VS Code + SweetPad + XcodeGen 开发 iOS 应用的完整指南
ios·swiftui·xcode