我正在尝试使用 SwiftUI 来制作它,以便如果我点击一个圆圈、图像或类似的东西,它将偏移到某个位置,如果我再次点击,它会回到该位置,同样来回切换。我找到了一个教程,教我如何切换背景颜色。 https://www.ioscreator.com/tutorials/swiftui-gesture-tutorial .如果你懒得看,基本上代码是这样的:
struct ContentView: View {
// 1.
@State private var didTap: Bool = false
var body: some View {
// 2.
Text("Tap me")
.frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
// 3.
.gesture(TapGesture()
.onEnded {
self.didTap.toggle()
}
)
// 4.
.background(didTap ? Color.blue : Color.red)
}
}
我改变了
Text("Tap me")
.frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
到
Circle()
.frame(width: 100, height: 100)
.foregroundColor(Color.red)
我想知道是否有办法做到这一点,而不是
.background(didTap ? Color.blue : Color.red)
我可以将 TapGesture bool 变量合并到 .offset(x: __, y: __)
不知何故。
最佳答案
我希望这是您正在寻找的解决方案,我也改变了您添加点击手势的方式。
struct TestView: View {
@State private var didTap: Bool = false
private var xOffset: CGFloat {
return didTap ? 10.0 : 0.0
}
var body: some View {
// 2.
Circle()
.frame(width: 100, height: 100)
.foregroundColor(Color.red)
.onTapGesture {
self.didTap.toggle()
}
//The x-offset depends on didTap State
.offset(x: xOffset, y: 0.0)
}}
关于ios - 如何使用点击手势来偏移图像或形状 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62351494/