iOS SwiftUI应用陷入无限循环致CPU100%占用,求排查原因
SwiftUI拖拽交互引发无限循环与CPU满负载问题求助
问题现象
开发iOS SwiftUI应用时遇到棘手问题:开启ReactanceView的frame宽度设置后,应用陷入无限循环,CPU占用率飙升至100%,完全无响应。
应用设计意图
通过SwiftUI构建带拖拽交互的UI:HStack容器内包含左右两个ReactanceView和中间可水平拖拽的DraggingView,期望拖拽中间视图时,左右ReactanceView的宽度随之动态增减。
已排查情况
全面检查代码,未发现明显的无限循环或递归函数,且DragGesture的终止条件设置正确,但仍无法定位问题根因。
相关代码片段
import SwiftUI struct ContentView: View { @State private var xMovement: CGFloat = 0.0 var body: some View { HStack(spacing: 20) { ReactanceView(width: 100 + xMovement, color: .blue) DraggingView(xMovement: $xMovement) .gesture(DragGesture() .onChanged { value in // Record the x-axis movement when the drag occurs xMovement = value.translation.width } .onEnded { _ in // Reset the x-axis movement when the drag ends xMovement = 0.0 } ) ReactanceView(width: 100 - xMovement, color: .blue) } .padding() } } struct ReactanceView: View { var width: CGFloat var color: Color var body: some View { // Replace this with your custom reactance view (e.g., Text, Image, etc.) Text("Reactance") .padding() //.frame(width: width, height: 100) // <---- uncommenting this will cause infinite loop .background(color) .foregroundColor(.white) } }
请求技术社区帮忙定位无限循环及CPU满负载的根本原因。
内容的提问来源于stack exchange,提问作者János
相关产品推荐
相关产品推荐

