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)") } } } }
界面渲染正常:
但控制台会两次打印:
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
相关产品推荐
相关产品推荐

