更改按钮锚点SwiftUI [英] Change Button Anchor Point SwiftUI

查看:152
本文介绍了更改按钮锚点SwiftUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改确定Button中心的锚点.以下代码将按钮放置在框架的左上角.

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)

如果我改用.offset,那么它将起作用.但我希望它位于框架的中心.有没有办法改变锚点?

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?

推荐答案

您可能需要打开父容器的框架,以便可以使用框架对齐.

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

这是AlignmentGuide的另一个粗糙但较快的版本.

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.

这篇关于更改按钮锚点SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆