xcode 无法在swiftui的切换中放置布尔值

xam8gpfp  于 2023-02-13  发布在  Swift
关注(0)|答案(1)|浏览(152)

嘿,所有我一直试图解决这个问题的2天了,只是似乎不能得到我正在寻找。
我的工作代码:

struct User: Decodable {
    let name: String
    let description: String
    let isOn: Bool
}

struct ContentView: View {
    @State var users = [User]()
    
    var body: some View {
        List{
            ForEach(users, id: \.name) { item in
                HStack {
                    Toggle(isOn: .constant(true)) {
                        Label {
                            Text(item.description)
                        } icon: {
                            //list.img
                        }
                    }
                }.padding(7)
            }
        }
        .onAppear(perform: loadData)
    }
    
    func loadData() {
        guard let url = URL(string: "https://-----.---/jsontest.json") else {
            print("Invalid URL")
            
            return
        }
        let request = URLRequest(url: url)
        
        URLSession.shared.dataTask(with: request) {data, response, error in
            if let data = data {
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .iso8601
                
                if let decodedResponse = try?
                    decoder.decode([User].self, from: data) {
                    DispatchQueue.main.async {
                        self.users = decodedResponse
                    }
                    
                    return
                }
            }
            
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }
}

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

Json的拉力看起来像这样:

{
   "name": "J",
   "description": "Echo Show",
   "isOn": true
},...

就像我上面说的,这段代码按原样工作。我遇到的问题是切换部分。它似乎没有发生在item. isOn上,用于查看它的true还是false。它唯一喜欢的是**. constant()。当然,这对我的情况不起作用,因为我需要将切换更改为true或false。
如果它不是
. constant**,则具有error
无法将类型"Bool"的值转换为所需的参数类型"Binding"
如果我这么做也许可以

@State var ison = false

var body: some View {
    List{
        ForEach(users, id: \.name) { item in
            HStack {
                Toggle(isOn: $ison)) {

这似乎消除了那个错误...但是它怎么能以那种方式得到为isOn循环的值呢?
我错过了什么?

yxyvkwin

yxyvkwin1#

试试这个方法,把isOn变成User中的var,然后使用bindingsForEachToggle中的$,对我来说是有效的:

struct User: Decodable {
    let name: String
    let description: String
    var isOn: Bool  // <-- here
}

struct ContentView: View {
    @State var users = [User]()
    
    var body: some View {
        List{
            ForEach($users, id: \.name) { $item in   // <-- here
                HStack {
                    Toggle(isOn: $item.isOn) {  // <-- here
                        Label {
                            Text(item.description)
                        } icon: {
                            //list.img
                        }
                    }
                }.padding(7)
            }
        }
        .onAppear(perform: loadData)
    }
    
    func loadData() {
        guard let url = URL(string: "https://-----.---/jsontest.json") else {
            print("Invalid URL")
            
            return
        }
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) {data, response, error in
            if let data = data {
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .iso8601
                if let decodedResponse = try?
                    decoder.decode([User].self, from: data) {
                    DispatchQueue.main.async {
                        self.users = decodedResponse
                    }
                    return
                }
            }
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }
}

相关问题