本文介绍了为什么MagnificationGesture在SwiftUI中只更新一次状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望以下视图对放大手势做出响应,但仅在第一次使用时有效.可以按预期将视图放大,但是在释放视图之后,后续的触摸不会触发手势.
I wish to have the following view respond to the magnification gestures, but it only works the first time.The view can be magnified as expected, but after the view is released, subsequent touches do not trigger the gesture.
有没有办法让手势连续工作?
Is there a way to have the gesture work continuously?
struct Card: View {
@State var magScale: CGFloat = 1
var magnification: some Gesture {
MagnificationGesture().onChanged { gesture in magScale = gesture }
}
var body: some View {
Rectangle()
.frame(width: 200, height: 200, alignment: .center)
.scaleEffect(self.magScale)
.gesture(magnification)
}
}
使用该视图的方式如下:
The view is used like so:
struct ContentView: View {
var body: some View {
ZStack {
Color.blue
Card()
}
}
}
推荐答案
这是一个解决方案.已通过 Xcode 12 (对于低于此版本的某些语法可能需要调整)进行测试
Here is a solution. Tested with Xcode 12 (for below version some syntax might needed adapting)
struct Card: View {
@State var magScale: CGFloat = 1
@State var progressingScale: CGFloat = 1
var magnification: some Gesture {
MagnificationGesture()
.onChanged { progressingScale = $0 }
.onEnded {
magScale *= $0
progressingScale = 1
}
}
var body: some View {
Rectangle()
.frame(width: 200, height: 200, alignment: .center)
.scaleEffect(self.magScale * progressingScale)
.gesture(magnification)
}
}
这篇关于为什么MagnificationGesture在SwiftUI中只更新一次状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!