我正在尝试使用 SwiftUI 制作一个可移动的按钮。从它看起来这应该可以工作。我曾尝试将带有文本的按钮放在另一个 ZStack 中,并且有一秒钟它正在工作,但是一旦我释放按钮,拖动就停止了,我不能再拖动了。我注意到尽管按钮已移动,但水龙头仍留在中心。拖动看起来也有问题。
struct CircleButton: View {
@State private var dragAmount = CGSize.zero
var body: some View {
ZStack {
Button(action: performAction){
ZStack {
Circle()
.foregroundColor(.blue)
.frame(width: 100, height: 100)
Text("Move me")
.foregroundColor(.white)
.font(.system(.caption, design: .serif))
}
}
.animation(.default)
.offset(self.dragAmount)
}
.gesture(
DragGesture()
.onChanged { self.dragAmount = $0.translation})
}
func performAction(){
print("button pressed")
}
}
我试过这个:
struct CircleButton: View {
@State private var dragAmount = CGSize.zero
var body: some View {
ZStack {
ZStack {
Button(action: performAction){
Circle()
.foregroundColor(.blue)
.frame(width: 100, height: 100)
}
Text("Tap me")
}
.offset(self.dragAmount)
.animation(.default)
}
.gesture(
DragGesture()
.onChanged{ self.dragAmount = $0.translation})
}
func performAction(){
print("button pressed")
}
}