SwiftUI - 将按钮内容对齐到左侧

11

我有一个设计看起来像这样:

图片描述

当我把它包裹在按钮里时,图像和“HOME”文本向中心移动:

图片描述

我想保持内容左对齐,但我遇到了问题。这是构成此组件的代码。

struct HomeSection: View {
var body: some View {
    Button(action: {

    }) {
        Group {
            Spacer().frame(width: 0, height: 36.0, alignment: .topLeading)
            HStack {
                Image("home")
                    .resizable()
                    .frame(width: 24, height: 24)
                    .foregroundColor(.navigationTextGrey)

                Text("HOME")
                    .bold()
                    .font(.system(size: 17.0))
                    .foregroundColor(Color.navigationTextGrey)
                    .padding(.leading, 4.0)
            }
            Rectangle()
                .fill(Color.navigationTextGrey)
                .frame(width: UIScreen.main.bounds.width - 60, height: 1)
                .padding(.top, 6.0)
        }
    }
}
}
4个回答

14

您可以在 HStack 中添加一个 Spacer,并添加填充以使房屋图像与矩形对齐。

var body: some View {
    Button(action: {
    }) {
        Group {
            Spacer().frame(width: 0, height: 36.0, alignment: .topLeading)
            HStack {
                Image("home")
                    .resizable()
                    .frame(width: 24, height: 24)
                    .foregroundColor(.navigationTextGrey)
                    .padding(.leading, 30.0)
                Text("HOME")
                    .bold()
                    .font(.system(size: 17.0))
                    .foregroundColor(Color.navigationTextGrey)
                    .padding(.leading, 4.0)
                Spacer()
            }
            Rectangle()
                .fill(Color.navigationTextGrey)
                .frame(width: UIScreen.main.bounds.width - 60, height: 1)
                .padding(.top, 6.0)
        }
    }
}

这是最终结果: 在此输入图片描述

另外,你可以使用Divider()代替矩形,以便清理你的代码:

Divider()
    .padding([.leading, .trailing], 30)

5

是的,这个可以大大精简。

var body: some View {
    Button(action: {
    }) {
        VStack(spacing: 6) {
            HStack(spacing: 4) {
                Image("home")
                    .resizable()
                    .frame(width: 24, height: 24)
                Text("HOME")
                    .bold()
                    .font(.system(size: 17.0))
                Spacer()
            }
            Divider()
        }
    }
    .foregroundColor(.navigationTextGrey)
    .padding([.leading, .trailing], 30)
}

2
你应该尝试为HStack添加Spacer和对齐方式。"最初的回答"
        HStack() {
            Image("home")
                .resizable()
                .frame(width: 24, height: 24)
                .foregroundColor(.navigationTextGrey)

            Text("HOME")
                .bold()
                .font(.system(size: 17.0))
                .foregroundColor(Color.navigationTextGrey)
                .padding(.leading, 4.0)

            Spacer()
            }

HStack 没有前导对齐。 - sfung3

1
尝试使用最大宽度为.infinity的间隔符。
Spacer().frame(maxWidth:.infinity)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接