SpringN
SpringN

Reputation: 954

Change Button Anchor Point SwiftUI

I'm attempting to alter the anchor point for what determines the center of a Button. The following code puts the button at the top left corner of the frame.

Button(action: {
            print(self.note)
        }) {
            Text(note)
        }
        .position(x: 0.0, y: 0.0)

If I use .offset instead, then it will work. I would like it to be centered within it's frame though. Is there a way to change the anchor point?

Upvotes: 3

Views: 2839

Answers (1)

E.Coms
E.Coms

Reputation: 11531

You may need to turn on the frame of the parent container, so that you can use frame alignment.

    var body: some View{

    GeometryReader{ p in
    VStack{
    Button(action: {
    }) {
        Text("note")
        }
    }.frame(width: p.size.width, height: p.size.height, alignment: .topLeading)
    }
}

Here is another rough but faster version with AlignmentGuide.

  var body: some View{
    VStack(alignment: .leading){
    Text("")
    Button(action: {
    }) {
        Text("simple version button")
    }.background(Color.red).alignmentGuide(.leading) { v in
        return  -v[.trailing]
    }}.position()
}

Hope you can have a better answer.

Upvotes: 3

Related Questions