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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:15:23