首页 > 解决方案 > 在 swiftUI 中禁用特定的行/按钮

问题描述

我有这个代码。我只想在名称为“Aditya”时禁用点击,其余的都是可点击的。我目前的试用版不起作用。如何根据某些属性禁用特定的行/按钮。在这种情况下,名称为“Aditya”

import SwiftUI

struct ContentView: View {
    
    var someelements = ["Aditya" , "Kappor" , "Chattarjee", "Mithun"]
    var body: some View {
        ForEach (self.someelements , id: \.self ) { something in
            EditForm(name: something)
            //Below is my trial that do not work.
            if something == "Aditya" {
                self.disabled(true)
            }
        }
    }
}


struct EditForm : View {
    var name : String
    var body: some View {
        Group {
            Button (action: {
                //some action
            }) {
                HStack {
                    Text(self.name)
                        .scaledToFit()
                        .foregroundColor(.blue)
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

标签: swiftswiftui

解决方案


struct ContentView: View {
    var someelements = ["Kappor" , "Chattarjee", "Mithun", "Aditya"]
    var body: some View {
        List {
            ForEach (self.someelements , id: \.self ) { value in
                Button(action: {
                    print("tapped")
                }, label: {
                    Text("\(value)")
                })
                .disabled(value == "Aditya") // Disable tap action only for that value here. 
            }
        }
    }
}

推荐阅读