简体   繁体   中英

Initial position of a SwiftUI view

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.

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)
        }
    }
}

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
                    }
            }
        }
    }
}

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 !!
    }

// ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM