3

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I borrowed some of your code from your first answer, but instead of using the line with ".frame" I used ".position(x: p.size.height, y: p.size.width)" and this corrected my problem. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.