cpu 在手势后放置偏移量时全速运行

问题描述 投票:0回答:1

我想沿 y 轴拖动图像。这看起来很简单。但是我错误地将“偏移量”放在“手势”之后。然后 cpu 全速运行,UI 变得无响应。

通过在“手势”之前重新排序“偏移量”,一切都可以。但是我想不通。

struct ContentView: View {
    @State private var currentPosition: CGSize = .zero
    @State private var newPosition: CGSize = .zero
    var body: some View {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
//                .offset(x: currentPosition.width, y: currentPosition.height)
                .gesture(DragGesture()
                    .onChanged { value in
                        print("DragEffectViewModifier-ondrag")
                        currentPosition = CGSize(width: 0, height: value.translation.height + newPosition.height)
                    }
                    .onEnded { value in
                        newPosition = currentPosition
                    })
                .offset(x: currentPosition.width, y: currentPosition.height)
    }
}

编辑:

控制台反复显示“DragEffectViewModifier-ondrag”。是什么导致了“循环行为”?当“offset”置于“gesture”下方时,它会使 cpu 全速运行,UI 变得无响应

ios swiftui gesture
1个回答
0
投票

我离开了一个系统来尝试你的代码,但看着它我认为这样的事情正在发生......结构被创建,一旦创建,状态变量被初始化,这导致 body var 被评估,当它被评估时,DragGesture 也被重新创建并初始化它的 onChanged,它重写 currentPostion 导致 body var 被重新评估,它重新创建 DragGesture,等等。

为了确认或否定我的推理,我会将 DragGesture 移动为身体外部的 var,然后将手势注入为类似 .gesture(dragGesture) 的东西。这似乎是我在手势使用示例中看到的那种模式。想法是将手势作为半单例,而不是每次评估 body var 时都重新创建新手势。

只是一个猜测。

© www.soinside.com 2019 - 2024. All rights reserved.