【问题标题】:make a button that appends structs to an array in swift制作一个快速将结构附加到数组的按钮
【发布时间】:2020-07-19 18:18:43
【问题描述】:

我正在尝试使用 swift 制作一个 macOS 列表/待办事项应用程序,并希望添加一个按钮,将结构添加到数组中,但它显示此错误:“不能在不可变值上使用 mutating member: 'self' is不可变” 这是我的代码


import SwiftUI

struct Lists{
    var title : String
    var id = UUID()
}


struct SidebarView: View {
    var list = [Lists(title: "one"),Lists(title: "two"),Lists(title: "three")]
    
    
    var body: some View {
        
       List{

            Button(action:{
                let item = Lists(title:"hello")
                list.append(item)
            }) {
                Text("add")
            }

        
            ForEach(list, id : \.id ){ item in
                NavigationLink(destination:DetailView(word:item.title)){
                    Text(item.title)
                }
            }
        }
       .listStyle(SidebarListStyle())
       .frame(maxWidth:200)
                  
    }
}

struct SidebarView_Previews: PreviewProvider {
    static var previews: some View {
        SidebarView()
    }
}

说 list.append 的代码是错误

【问题讨论】:

    标签: arrays swift macos swiftui


    【解决方案1】:

    您需要将list 声明为@State 变量。

    @State var list = [Lists(title: "one"),Lists(title: "two"),Lists(title: "three")]
    

    然后将新的item 附加到list

    Button(action:{
        let item = Lists(title:"hello")
        self.list.append(item)
    }) {
        Text("add")
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 2016-10-10
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多