gpt4 book ai didi

swift - 如何使用 SwiftUI 使按钮可拖动/移动?

转载 作者:行者123 更新时间:2023-12-04 15:59:40 27 4
gpt4 key购买 nike

我正在尝试使用 SwiftUI 制作按钮可移动。从它看起来这应该工作。我曾尝试将带有文本的 Button 放入另一个 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")
}
}

最佳答案

这是可能的方法的演示。经测试适用于 Xcode 11.4/iOS 13.4
demo
另请参阅内联注释。

struct CircleButton: View {
@State private var dragAmount: CGPoint?
var body: some View {
GeometryReader { gp in // just to center initial position
ZStack {
Button(action: self.performAction) {
ZStack {
Circle()
.foregroundColor(.blue)
.frame(width: 100, height: 100)
Text("Move me")
.foregroundColor(.white)
.font(.system(.caption, design: .serif))
}
}
.animation(.default)
.position(self.dragAmount ?? CGPoint(x: gp.size.width / 2, y: gp.size.height / 2))
.highPriorityGesture( // << to do no action on drag !!
DragGesture()
.onChanged { self.dragAmount = $0.location})
}
.frame(maxWidth: .infinity, maxHeight: .infinity) // full space
}
}

func performAction() {
print("button pressed")
}
}

关于swift - 如何使用 SwiftUI 使按钮可拖动/移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61264499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com