代码之家  ›  专栏  ›  技术社区  ›  Manngo

使用日历填充SwiftUI选取器

  •  0
  • Manngo  · 技术社区  · 1 年前

    我正在尝试用日历列表填充SwiftUI选择器。

    据我所知,这个过程应该是这样的:

    • 声明日历数组:
    • 在视图中填充阵列 onAppear 方法
    • 从数组中填充选取器。

    如果没有一些根本性的错误,我什么都做不了。我的代码是这样的:

    在顶层创建变量:

    let eventStore : EKEventStore = EKEventStore()
    let sources = eventStore.sources
    
    var calendars: [EKCalendar] = []
    

    .onAppear() 方法填充变量:

    for source in sources {
        calendars = calendars + source.calendars(for: .event).sorted{ $0.title < $1.title }
    }
    

    填充选取器:

    struct ContentView: View {
        @Binding var calendar: EKCalendar!
        
        var body: some View {
            VStack {
                Picker("Select a calendar", selection: $calendar) {
                    
    //              ForEach(calendars) { calendar in
    //                  Text("hahaha")
    //                  Text(calendar.title)
    //              }
                }
                .pickerStyle(.menu)
            }
        }
    }
    

    上面注释掉的代码不起作用。如何填充选取器?

    1 回复  |  直到 1 年前
        1
  •  1
  •   workingdog support Ukraine    1 年前

    尝试此示例方法,选择 calendar calendars 在您的 ContentView ,至少作为一种测试。 注意拥有的重要性 .tag(Optional(calendar)) 在Picker中。

    当然,您需要在应用程序沙盒设置中启用日历, 并且在您的EKEventStore中有一些日历,否则您将只看到“无选择”。

    struct ContentView: View {
        @State private var calendar: EKCalendar? // <--- here
        @State private var calendars: [EKCalendar] = [] // <--- here
    
       let eventStore : EKEventStore = EKEventStore()
        
        var body: some View {
            VStack {
                Picker("Select a calendar", selection: $calendar) {
                    Text("no selection").tag(Optional<EKCalendar>.none)
                    ForEach(calendars, id: \.self) { calendar in
                        Text(calendar.title)
                            .tag(Optional(calendar)) // <--- here
                    }
                }
                .pickerStyle(.menu)
            }
            .onAppear {
                // --- here
                for source in eventStore.sources {
                    calendars = calendars + source.calendars(for: .event).sorted{ $0.title < $1.title }
                }
                print("----> calendars: \(calendars.count)") // for testing info
            }
        }
    }
    

    注意,您还需要授予(用户请求)访问各种 日历。