Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

swift - How can I use the @Environment(.calendar) in a View to initialize a @State variable?

I have a calendar view like so:

struct CalendarView: View {
    @Environment(.calendar) var calendar
    @State var daysForMonthView: [DateInterval]
    ...
}

where i need to initialize the daysForMonthView array by using the @Environment(.calendar). How can I do that?

Trying to do:

init() {
    _daysForMonthView = State(initialValue: calendar.daysForMonthViewContaining(date: Date()))
}

produces a Variable 'self.daysForMonthView' used before being initialized -error.

question from:https://stackoverflow.com/questions/65852568/how-can-i-use-the-environment-calendar-in-a-view-to-initialize-a-state-vari

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to assign all the properties before you can access the @Environment. For this reason you can't use calendar to initialise daysForMonthView.

A possible solution is to use onAppear:

struct CalendarView: View {
    @Environment(.calendar) private var calendar
    @State private var daysForMonthView: [DateInterval] = [] // assign empty
    
    var body: some View {
        //...
        .onAppear {
            daysForMonthView = calendar...
        }
    }
}

If for some reason you need calendar to be available in the init, you can pass it as a parameter in init:

struct ContentView: View {
    @Environment(.calendar) private var calendar

    var body: some View {
        CalendarView(calendar: calendar)
    }
}

struct CalendarView: View {
    private let calendar: Calendar
    @State private var daysForMonthView: [DateInterval]
    
    init(calendar: Calendar) {
        self.calendar = calendar
        self._daysForMonthView = .init(initialValue: calendar...)
    }

    //...
}

Note: the downside of this approach is that a change to the calendar will reinitialise the whole CalendarView.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...