Change Button Anchor Point SwiftUI

梦想的初衷 提交于 2020-12-06 21:47:03

问题


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:


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.



来源:https://stackoverflow.com/questions/58616727/change-button-anchor-point-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!