Home > Net >  Initial position of a SwiftUI view
Initial position of a SwiftUI view

Time:06-21

I have a view that gets dragged around the screen by updating its position. I'm having a hard time setting its initial position via an argument.

I'm trying to use the commented out var initialPosition argument.

Any help is greatly appreciated.

struct FloatingView<Content:View>: View {
    let content: Content
    var hidden: Bool
    var size: CGSize
//    var initialPosition: CGPoint

    @State private var location: CGPoint = CGPoint(x:65, y:100)

    var simpleDrag: some Gesture {
        DragGesture()
            .onChanged { value in
                self.location = value.location
            }
    }

    var body: some View {
        if hidden == false {
            content
                .foregroundColor(.pink)
            //            .frame(width: 100, height: 100)
                .position(location)
                .gesture(simpleDrag)
        }
    }
}

CodePudding user response:

It is possible to do this in view's init, like

struct FloatingView<Content:View>: View {
    private let content: Content
    private let hidden: Bool
    private let size: CGSize

    @State private var location: CGPoint

    init(content: Content, hidden: Bool, size: CGSize, initialPosition: CGPoint) {
        self.content = content
        self.hidden = hidden
        self.size = size
        self._location = State(initialValue: initialPosition)  // << here !!
    }

// ...
}

CodePudding user response:

You could use a GeometryReader in order to read the frame of the View, get its center & assign it to initialPosition.

Try this:

struct FloatingView<Content:View>: View {
    let content: Content
    var hidden: Bool
    var size: CGSize
    @State var initialPosition: CGPoint
    @State private var location: CGPoint = CGPoint(x:65, y:100)
    var simpleDrag: some Gesture {
        DragGesture()
            .onChanged { value in
                self.location = value.location
            }
    }
    var body: some View {
        GeometryReader { proxy in
            if hidden == false {
                content
                    .foregroundColor(.pink)
                  //.frame(width: 100, height: 100)
                    .position(location)
                    .gesture(simpleDrag)
                    .onAppear {
                        initialPosition = proxy.frame(in: .global).center
                    }
            }
        }
    }
}
  • Related