ios - 如何使用点击手势来偏移图像或形状 View

标签 ios swift swiftui uitapgesturerecognizer

我正在尝试使用 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/

相关文章:

ios提前设置UIDatePicker时间

ios - 永远不会调用 CAAnimationDelegate 委托(delegate)

ios - 在 Swift 中实现 SRWebSocketDelegate

xcode - SwiftUI Canvas 预览编译错误: Undefined symbols for architecture x86_64

ios - SwiftUI MVVM : child view model re-initialized when parent view updated

ios - 克服 'Limit Ad Tracking' - iOS

ios - 从 Split ViewController 中的 Master ViewController 转到另一个 View Controller

ios - 要将此应用配置为 iOS 路由应用,应用的 Info.plist 必须包含 MKDirectionsApplicationSupportedModes 键

ios - 将 float 添加到十进制数

ios - SwiftUI 中的自定义模式转换