如何防止在swiftUI中同时点击两个按钮?

时间:2019-11-12 19:13:46

标签: swiftui

在swift或Objective-c中,我可以将ExclusiveTouch属性设置为true或YES,但是如何在swiftUI中实现呢?

2 个答案:

答案 0 :(得分:-1)

可以像下面这样处理:

struct ContentView: View {

    @State private var isEnabled = false

    var body: some View {
        VStack(spacing: 50) {
            Button(action: {
                self.isEnabled.toggle()
            }) {
                Text("Button 1")
            }
            .padding(20)                
            .disabled(isEnabled)


            Button(action: {
                self.isEnabled.toggle()
            }) {
                Text("Button 2")
            }
            .padding(50)
            .disabled(!isEnabled)
        }
    }
}

答案 1 :(得分:-1)

Xcode 11.3

在结构exclusiveTouch中设置isMultipleTouchEnabledinit()属性,或将其放置在AppDelegate.swift中,用于整个应用程序:

struct ContentView: View {

init() {

        UIButton.appearance().isMultipleTouchEnabled = false
        UIButton.appearance().isExclusiveTouch = true

        UIView.appearance().isMultipleTouchEnabled = false
        UIView.appearance().isExclusiveTouch = true

        //OR

        for subView in UIView.appearance().subviews {

            subView.isMultipleTouchEnabled = false
            subView.isExclusiveTouch = true

            UIButton.appearance().isMultipleTouchEnabled = false
            UIButton.appearance().isExclusiveTouch = true
        }
    }

var body: some View {

VStack {
     Button(action: {
                print("BTN1")
            }){
                Text("First")
            }

     Button(action: {
                print("BTN2")
            }){
                Text("Second")
            }
   }  
 }
}