SwiftUI:表单行中的多个按钮

时间:2019-10-26 21:33:41

标签: ios swift xcode swiftui

我有一个包含许多项目的表单,并且我想拥有多个按钮的行之一。但是,在轻按一个按钮时,整个行将亮起,并且将调用该行中所有按钮的所有操作。

如何在“表单”行中使按钮不突出整个行,而只调用其自己的操作?

(也:如何确保整个行都不会变为可点击状态?)

示例代码:在下面的示例中,即使从通读开始,您希望一旦单击一个按钮,另一个按钮都将被禁用,实际上,两个按钮都被禁用,因为两个按钮动作均被调用。

示例屏幕截图:在这里我点击了“ A!”仅,但整行都亮起,并且两个按钮动作都被调用 Here I tapped "A!" only, yet the entire row lights up, and both button actions are called

import SwiftUI

struct TwoButtonsInAFormRowView: View {

    @State private var buttonADisabled = false
    @State private var buttonBDisabled = false


    var body: some View {
        Form {
            ForEach(0..<5) { _ in
                HStack {
                    Text("We have many rows like this....")
                    Spacer()
                    TextField("Like this", text: .constant("value"))
                        .multilineTextAlignment(.trailing)
                }
            }
            HStack {
                Text("Tap one (and only one) button")

                Spacer()

                Button(action: {
                    self.buttonBDisabled = true
                }) {
                    Text("A!")
                }
                .disabled(self.buttonADisabled)

                Button(action: {
                    self.buttonADisabled = true
                }) {
                    Text("B!")
                }
                .disabled(self.buttonBDisabled)
            }
        }
    }
}

#if DEBUG
struct TwoButtonsInAFormRowViewPreviews: PreviewProvider {

    static var previews: some View {
        return TwoButtonsInAFormRowView()
                .previewLayout(.sizeThatFits)
    }
}
#endif

0 个答案:

没有答案