SwiftUI:处理HStack中按钮之间的空间

时间:2020-10-17 03:15:44

标签: swiftui vstack swiftui-button

我正在实现一个警报视图,该警报视图有两个按钮:

enter image description here

Submit是一个按钮,而Cancel是另一个按钮,但是可以靠近中心。有控制按钮位置的方法吗?

这是我的实现方式

var body: some View {
    ZStack {
        VStack{
            Text(text)
            TextField("", text: $text, onEditingChanged: {
                self.typing = $0
            }, onCommit: {
                self.text = self.text
            })
            .textFieldStyle(RoundedBorderTextFieldStyle())
            HStack {
                Button(action: {
                    
                    
                }, label: {
                    Text("Submit")
                })
                Button(action: {
                    
                }, label: {
                    Text("Cancel")
                })
                
            }
        }
        .padding()
        .frame(width: screenSize.width * 0.7, height: screenSize.height * 0.3)
        .background(Color(red: 0.9268686175, green: 0.9416290522, blue: 0.9456014037, opacity: 1))
        .clipShape(RoundedRectangle(cornerRadius: 20.0, style: .continuous))
        .offset(y: isShown ? 0 : screenSize.height)
        .animation(.spring())
        .shadow(color: Color(red: 0.8596749902, green: 0.854565084, blue: 0.8636032343, opacity: 1), radius: 6, x: -9, y: -9)
        
    }
}

你们中的任何人都知道如何操纵按钮的分离吗?

3 个答案:

答案 0 :(得分:0)

  1. 您可以在按钮所在的HStack中添加间距:

         HStack(spacing: 20) {
    
  2. 您可以在按钮上添加填充:

             Button(action: {
                 //action
             }, label: {
                 Text("Button")
             })
             .padding(.horizontal, 20)
    
  1. 您可以设置按钮的框架:

             Button(action: {
                 //action
             }, label: {
                 Text("Button")
             })
             .frame(width: 100)
    
  2. 您可以在HStack中添加一个分隔符:

             HStack {
                 Button...
                 Spacer()
                 Button...
             }
    

答案 1 :(得分:0)

我认为两个按钮之间的垫片会为您提供帮助。在您的HStack中....

HStack {
 
Button(action: {
                        
                        
                    }, label: {
                        Text("Submit")
                    })
                    Spacer()
                    Button(action: {
                    
                    }, label: {
                        Text("Cancel")
                    })
                    
                }

答案 2 :(得分:0)

除了上面惊人的答案之外,您还可以使用以下代码设置间隔的确切长度:

HStack {
             Button...
             Spacer().frame(height: 30)
             Button...
}

将框架高度添加到间隔器将控制它尽可能不扩展;)