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

SwiftUI中Button标签重复渲染的问题咨询

SwiftUI Button标签重复渲染问题

目前发现SwiftUI的Button标签存在重复渲染情况,暂不清楚问题出现的具体时间。以下述代码为例:

struct ContentView: View {
    @State var active = false
    var body: some View {
        Button {
            active.toggle()
        } label: {
            Text("Toggle")
                .onChange(of: active) { newValue in
                    print("Active changed to: \(newValue)")
                }
        }
    }
}

界面渲染正常:
显示Toggle的按钮

但控制台会两次打印:

Active changed to: true
Active changed to: true

为何"Active changed to: true"会被打印两次?

我推测SwiftUI会两次计算标签内容,但仅在第二次渲染时显示标签。通过UIViewRepresentable测试发现,本应仅调用一次的makeUIView函数被调用了两次:

struct ContentView: View {
    @State var active = false
    var body: some View {
        Button {
            active.toggle()
        } label: {
            InnerViewRepresentable()
        }
    }
}

struct InnerViewRepresentable: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        print("Making view")
        return UIView()
    }

    func updateUIView(_: UIView, context: Context) {}
}

控制台输出:

Making view
Making view

请问各位有什么思路?我当前使用的是Xcode 14.0 beta 3(14A5270f),运行在iOS 16.0模拟器上。这可能是个小问题,但它破坏了我一些依赖onChange的视图修饰符。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:43:27