首页 > 解决方案 > 如何在 SwiftUI 中使视图宽度等于超级视图

问题描述

我有Button

在此处输入图像描述

struct ContentView : View {
    var body: some View {
        HStack {
            Button(action: {}) {
                Text("MyButton")
                    .color(.white)
                    .font(Font.system(size: 17))
            }
            .frame(height: 56)
            .background(Color.red, cornerRadius: 0)
        }
    }
}

但我想把它固定在 superview 的边缘(拖到 superview 的尾随和前导)。像这样:

在此处输入图像描述

HStack对我没有帮助,它正在期待。固定frame或宽度等于UIScree.size不是灵活的解决方案。

标签: swiftuiios13

解决方案


你需要使用.frame(minWidth: 0, maxWidth: .infinity)修饰符

添加下一个代码

        Button(action: tap) {
            Text("Button")
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(Color.red)
        }
        .padding([.leading, .trailing], 20)

填充修饰符将允许您在边缘留出一些空间。

请记住,修饰符的顺序很重要。因为修饰符实际上是包装视图的函数(它们不会更改视图的属性)


推荐阅读