I'm trying to write a reusable quick select field editor for a SwiftUI application. The code below only shows the error Variable 'self.fieldValue' used before initialized if the @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> is present. If I remove that, the view compiles fine. Anyone know why the presentationmode environment variable is causing this and how to fix it? I need the presentationmode env var so I can quickly pop the view once the user clicks on a button.
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@State var viewName = "Edit Field"
@Binding var fieldValue: Int
@State var fieldName: String = ""
var options: [Int]
init(title: String, field: String, value: Binding<Int>, list: [Int]) {
viewName = title
fieldName = field
_fieldValue = value
options = list
}
For full view code, see below.
import SwiftUI
struct CommonNumberEditView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@State var viewName = "Edit Field"
@Binding var fieldValue: Int
@State var fieldName: String = ""
var options: [Int]
init(title: String, field: String, value: Binding<Int>, list: [Int]) {
viewName = title
fieldName = field
_fieldValue = value
options = list
}
var body: some View {
ZStack {
Image("sky")
.resizable()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
.opacity(0.5)
VStack(alignment: .center, spacing: 5)
{
JumpLogNumberField(label: self.fieldName, val: self.$fieldValue)
ScrollView {
VStack(alignment: .center, spacing: 5) {
ForEach(options, id: \.self) { item in
Group {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text(String(item))
.foregroundColor(.black)
.padding(20)
}
.frame(minWidth:0, maxWidth: .infinity)
.background(Color.white.opacity(0.6))
}
}
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .top)
}
.padding(.top, 40)
.padding(.leading, 40)
.padding(.trailing, 40)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}.navigationBarTitle(viewName, displayMode: .inline)
}
}
struct CommonFieldEditView_Previews: PreviewProvider {
static var previews: some View {
CommonNumberEditView(title: "Edit Field", field: "Altitude", value: .constant(5000), list: [ 13500, 10000, 5500, 3500 ])
}
}