Increase/Decrease 通过拖动视图的边缘来水平调整视图的大小

Increase/Decrease the size of a view horizontally by dragging the edges of it

我见过一些类似的示例,例如 and How to resize UIView by dragging from its edges?,但我无法准确找到我正在寻找的与 SwiftUI 正确关联的内容

我有一个视图,我希望用户能够通过视图右侧的 'grab bar' 调整宽度。当用户向左(减小视图宽度)和向右(增加视图宽度)拖动此栏时。我该怎么做呢?

在示例中,RedRectangle 是我试图调整的视图,它包括 Rectangle 和用于调整大小的 Resizer。我在这里做错了什么?

此外,没有 渐变 animation/transition 帧 increased/decreased,它只是似乎跳跃。我怎样才能做到这一点?

此处链接的可重现示例:

import SwiftUI

struct ContentView: View {
    @State var resizedWidth: CGFloat?

    var body: some View {
        HStack(alignment: .center) {
            Spacer()
            RedRectangle(width: 175, resizedWidth: resizedWidth)
            Resizer()
                .gesture(
                    DragGesture()
                        .onChanged({ value in
                            resizedWidth = max(80, resizedWidth ?? 0 + value.translation.width)
                        })
                )
            Spacer()
        }
    }
}

struct RedRectangle: View {
    let width: CGFloat
    var resizedWidth: CGFloat?

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: resizedWidth != nil ? resizedWidth : width, height: 300)
            .frame(minWidth: 80, maxWidth: 400)
    }
}

struct Resizer: View {
    var body: some View {
        Rectangle()
            .fill(Color.blue)
            .frame(width: 8, height: 75)
            .cornerRadius(10)
    }
}
import SwiftUI

struct ContentView: View {
    let minWidth: CGFloat = 100
    @State var width: CGFloat?

    var body: some View {
        HStack(alignment: .center) {
            Spacer()
            RedRectangle(width: width ?? minWidth)
            Resizer()
                .gesture(
                    DragGesture()
                        .onChanged { value in
                            width = max(minWidth, width! + value.translation.width)
                        }
                )
            Spacer()
        }
        .onAppear {
            width = minWidth
        }
    }
}

struct RedRectangle: View {
    let width: CGFloat

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: width, height: 100)
    }
}

struct Resizer: View {
    var body: some View {
        Rectangle()
            .fill(Color.blue)
            .frame(width: 8, height: 75)
            .cornerRadius(10)
    }
}