Pre-enter text in a textfield in SwiftUI - xcode

I was able to solve my problem i had earlier on how to update data in Firestore via UI. Now the next problem:
I would like to have my Firebase-Stored Data pre-entered in a text field so you can just !edit! the text in the fields you want instead of writing all data new in every single field. As you can see, the only thing i was able to do, is getting the stored data in the text field as placeholder, which means you have to re-write all data in case you want to update just 1 field.
CODE:
import SwiftUI
import Firebase
struct ContentViewVier: View {
#ObservedObject var dataDrei = getDataZwei()
var body: some View {
NavigationView{
ZStack(alignment: .top){
GeometryReader{_ in
// Home View....
Text("Bitte Seriennummer eingeben").foregroundColor(.black)
}.background(Color("FarbeSeriennummerStartbildschirm").edgesIgnoringSafeArea(.all))
CustomSearchBarEdit(dataZwei: self.$dataDrei.datasZwei).padding(.top)
}.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
struct CustomSearchBarEdit : View {
#State var txt = ""
#Binding var dataZwei : [dataTypeZwei]
var body : some View{
VStack(spacing: 0){
HStack{
TextField("Nach Seriennummer suchen", text: self.$txt).opacity(100).foregroundColor(.black)
if self.txt != ""{
Button(action: {
self.txt = ""
}) {
Text("Abbrechen")
}
.foregroundColor(.black)
}
}.padding()
if self.txt != ""{
if
self.dataZwei.filter({$0.sn.lowercased() .contains(self.txt.lowercased())}).count == 0 {
Text("Es wurde kein Gerät mit dieser Seriennummer gefunden").foregroundColor(Color.red.opacity(0.6)).padding()
}
else{
List(self.dataZwei.filter{$0.sn.contains(self.txt.lowercased())}){j in
NavigationLink(destination: DetailZwei(data: j)) {
Text(j.sn)
}
Text(j.typ)
}.frame(height: UIScreen.main.bounds.height / 5)
}
}
}.background(Color.white)
.padding()
}
}
class getDataZwei : ObservableObject{
#Published var datasZwei = [dataTypeZwei]()
init() {
let db = Firestore.firestore()
db.collection("Geräte").getDocuments { (snap, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
for i in snap!.documents{
let id = i.documentID
let sn = i.get("Seriennummer") as! String
let objekt = i.get("Objekt") as! String
let str = i.get("Strasse") as! String
let pos = i.get("Position") as! String
let typ = i.get("Gerätetyp") as! String
let ida = i.get("Installation")as! String
let lg = i.get("LeasingOderGekauft")as! String
let la = i.get("LeasingAblaufdatum")as! String
let ga = i.get("GarantieAblaufdatum")as! String
let nr = i.get("Hausnummer")as! String
let plz = i.get("Postleitzahl")as! String
let ort = i.get("Ort")as! String
let vp = i.get("Verantwortlich")as! String
let tel = i.get("Telefonnummer")as! String
let zusatz = i.get("Zusätzlich")as! String
let ed = i.get("EingetragenDurch")as! String
let ldvds = i.get("LieferungBeiVDS")as! String
self.datasZwei.append(dataTypeZwei(id: id, sn: sn, pos: pos, typ: typ, ida: ida, lg: lg, la: la, ga: ga, objekt: objekt, str: str, nr: nr, plz: plz, ort: ort, vp: vp, tel: tel, zusatz: zusatz, ed: ed, ldvds: ldvds))
}
}
}
}
struct dataTypeZwei : Identifiable, Codable {
var id: String? = UUID().uuidString
var sn : String
var pos : String
var typ : String
var ida : String
var lg : String
var la : String
var ga : String
var objekt : String
var str : String
var nr : String
var plz : String
var ort : String
var vp : String
var tel : String
var zusatz : String
var ed : String
var ldvds : String
enum CodingKeys: String, CodingKey {
case sn = "Seriennummer"
case objekt = "Objekt"
case str = "Strasse"
case nr = "Hausnummer"
case ort = "Ort"
case vp = "Verantwortlich"
case tel = "Telefonnummer"
case pos = "Position"
case typ = "Gerätetyp"
case ida = "Installation"
case lg = "LeasingOderGekauft"
case la = "LeasingAblaufdatum"
case ga = "GarantieAblaufdatum"
case zusatz = "Zusätzlich"
case plz = "Postleitzahl"
case ed = "EingetragenDurch"
case ldvds = "LieferungBeiVDS"
}
}
struct DetailZwei : View {
var data : dataTypeZwei
#State var viewModel = GerätEditieren()
#State var serie: String? = nil
#Environment(\.presentationMode) var presentationMode
var body : some View {
NavigationView {
ScrollView {
Group {
Section(header: Text("Gerät")) {
Text("Seriennummer")
TextField(data.sn, text: $viewModel.gerät.sn).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Objekt")
TextField(data.objekt, text: $viewModel.gerät.objekt).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Gerätetyp")
TextField(data.typ, text: $viewModel.gerät.typ).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Geräteposition")
TextField(data.pos, text: $viewModel.gerät.pos).textFieldStyle(RoundedBorderTextFieldStyle())
}
Group {
Text("Installationsdatum")
TextField(data.ida, text: $viewModel.gerät.ida).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Leasing oder Gekauft?")
TextField(data.lg, text: $viewModel.gerät.lg).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Ablaufdatum Leasing")
TextField(data.la, text: $viewModel.gerät.la).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Ablaufdatum Garantie")
TextField(data.ga, text: $viewModel.gerät.ga).textFieldStyle(RoundedBorderTextFieldStyle())
}
Section(header: Text("Adresse")) {
Text("Strasse")
TextField(data.str, text: $viewModel.gerät.str).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Hausnummer")
TextField(data.nr, text: $viewModel.gerät.nr).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Postleitzahl")
TextField(data.plz, text: $viewModel.gerät.plz).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Ort")
TextField(data.ort, text: $viewModel.gerät.ort).textFieldStyle(RoundedBorderTextFieldStyle())
}
Section(header: Text("Kontakt")) {
Text("Ansprechperson")
TextField(data.vp, text: $viewModel.gerät.vp).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Telefonnummer")
TextField(data.tel, text: $viewModel.gerät.tel).textFieldStyle(RoundedBorderTextFieldStyle())
}
Section(header: Text("VDS")) {
Text("Eingetragen durch")
TextField(data.ed, text: $viewModel.gerät.ed).textFieldStyle(RoundedBorderTextFieldStyle())
Text("Lieferdatum VDS")
TextField(data.ldvds, text: $viewModel.gerät.ldvds).textFieldStyle(RoundedBorderTextFieldStyle())
}
Section(header: Text("Zusätzliche Informationen")) {
Text("Zusätzliche Informationen")
TextField(data.zusatz, text: $viewModel.gerät.zusatz).textFieldStyle(RoundedBorderTextFieldStyle())
}
}.padding()
.navigationBarTitle("Gerät bearbeiten", displayMode: .inline)
.navigationBarItems(leading: Button(action: { self.handleCancelTapped() }, label: {
Text("Abbrechen")
}),
trailing: Button(action: { self.handleDoneTapped() }, label: {
Text("Speichern")
})
// .disabled(!viewModel.modified)
)
}
}
}
func handleCancelTapped() {
dismiss()
}
func handleDoneTapped() {
let db = Firestore.firestore()
let docRef = db.collection("Geräte").document(data.id!)
print("setting data")
docRef.updateData(["Seriennummer": "\(viewModel.gerät.sn)", "Objekt": "\(viewModel.gerät.objekt)", "Strasse": "\(viewModel.gerät.str)", "Hausnummer": "\(viewModel.gerät.nr)", "Ort": "\(viewModel.gerät.ort)", "Verantwortlich": "\(viewModel.gerät.vp)", "Telefonnummer": "\(viewModel.gerät.tel)", "Position": "\(viewModel.gerät.pos)", "Gerätetyp": "\(viewModel.gerät.typ)", "Installation": "\(viewModel.gerät.ida)", "LeasingOderGekauft": "\(viewModel.gerät.lg)", "LeasingAblaufdatum": "\(viewModel.gerät.la)", "GarantieAblaufdatum": "\(viewModel.gerät.ga)", "Zusätzlich": "\(viewModel.gerät.zusatz)", "Postleitzahl": "\(viewModel.gerät.plz)", "EingetragenDurch": "\(viewModel.gerät.ed)", "LieferungBeiVDS": "\(viewModel.gerät.ldvds)"]){ (error) in
if let error = error {
print("error = \(error)")
} else if self.viewModel.gerät.sn == "" {
self.viewModel.gerät.sn = self.data.sn
}
else {
print("data uploaded successfully")
}
}
dismiss()
}
func dismiss() {
presentationMode.wrappedValue.dismiss()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentViewVier()
}
}

This belong to your viewModel to initialize the Published values with the exact value.
Another option is to set the State variables, which you pass to your TextField with the actual value.
#State var vp : String
init(data: Data) { 
self._vp = State(initialValue: data.vp) //<< here set the value from Firebase
}
TextField(data.vp, text: $vp).textFieldStyle(RoundedBorderTextFieldStyle())

Related

How to sort List ForEach Swiftui

Hi there
I'm newbie for SwiftUI, and I want to sort the "expireDate" , then use forEach to display the view according to the expireDate, how to???
sorry for my messy code, coding is really not easy.
will be much appreciate if someone can help
Here is the data
import Foundation
struct CardData: Identifiable, Codable {
let id: UUID
var cardName: String
var cardNumber: String
var expireDate: Date
var theme: Theme
var history: [History] = []
init(id: UUID = UUID(), cardName: String, cardNumber: String, expireDate: Date, theme: Theme) {
self.id = id
self.cardName = cardName
self.cardNumber = cardNumber
self.expireDate = expireDate
self.theme = theme
}
}
extension CardData {
struct Data {
var cardName: String = ""
var cardNumber: String = ""
var expireDate: Date = Date.now
var theme: Theme = .orange
}
var data: Data {
Data(cardName: cardName, cardNumber: cardNumber, expireDate: expireDate, theme: theme)
}
mutating func update(from data: Data) {
cardName = data.cardName
cardNumber = data.cardNumber
expireDate = data.expireDate
theme = data.theme
}
init(data: Data) {
cardName = data.cardName
cardNumber = data.cardNumber
expireDate = data.expireDate
theme = data.theme
id = UUID()
}
}
And here is the view
import SwiftUI
struct CardView: View {
#Binding var datas: [CardData]
#Environment(\.scenePhase) private var scenePhase
#State private var isPresentingNewCardView = false
#State private var newCardData = CardData.Data()
let saveAction: () -> Void
#EnvironmentObject var launchScreenManager: LaunchScreenManager
#State private var confirmationShow = false
var body: some View {
List {
ForEach($datas) { $data in
NavigationLink(destination: DetailView(cardData: $data)){
CardDataView(cardData: data)
}
.listRowBackground(data.theme.mainColor)
}
.onDelete(perform: deleteItems)
}
.navigationTitle("Expiry Date")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
Button(action: {
isPresentingNewCardView = true
}) {
Image(systemName: "plus")
}
.accessibilityLabel("New data")
}
.sheet(isPresented: $isPresentingNewCardView) {
NavigationView {
DetailEditView(data: $newCardData)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Dismiss") {
isPresentingNewCardView = false
newCardData = CardData.Data()
}
}
ToolbarItem(placement: .confirmationAction) {
Button("Add") {
let newData = CardData(data: newCardData)
datas.append(newData)
isPresentingNewCardView = false
newCardData = CardData.Data()
}
}
}
}
}
.onChange(of: scenePhase) { phase in
if phase == .inactive { saveAction() }
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
launchScreenManager.dismiss()
}
}
}
func deleteItems(at offsets: IndexSet) {
datas.remove(atOffsets: offsets)
}
}
Hi there
I'm newbie for SwiftUI, and I want to sort the "expireDate" , then use forEach to display the view according to the expireDate, how to???
sorry for my messy code, coding is really not easy.
will be much appreciate if someone can help
You can sort the datas in place, before you use it in the ForEach,
when you create the datas for example. Like this:
datas.sort(by: { $0.expireDate > $1.expireDate}).
Or
you can sort the datas just in the ForEach,
like this, since you have bindings,
ForEach($datas.sorted(by: { $0.expireDate.wrappedValue > $1.expireDate.wrappedValue})) { $data ...}
Note with this ForEach($datas.sorted(by: ...), when you do your func deleteItems(at offsets: IndexSet),
you will have to get the index in the sorted array, and delete the equivalent in the original one.
EDIT-1:
updated func deleteItems:
func deleteItems(at offsets: IndexSet) {
let sortedArr = datas.sorted(by: { $0.expireDate > $1.expireDate})
for ndx in offsets {
if let cardIndex = datas.firstIndex(where: { $0.id == sortedArr[ndx].id }) {
datas.remove(at: cardIndex)
}
}
}
Note you may want to put let sortedArr = datas.sorted(by: { $0.expireDate > $1.expireDate}) somewhere else (eg. .onAppear) instead of evaluating this, every time you use deleteItems

How can I use a list of names out of CoreData with a Picker in menuPickerStyle

I'm looking for a way to read a list of players from CoreData in order to select a single name with a menupickerstyle-picker. Displaying the entire list works fine.
this works fine:
Text("Number of players: (teams.count) ")
How con a display a single name?
Text("Players Name: (???????????) ")
Thx for any help.
Franz
//DataBase: teamsandscores Entity: Team, Attributes: id as UUID and player as String
class CoreDataManager {
let persistentContainer: NSPersistentContainer
init() {
persistentContainer = NSPersistentContainer(name: "teamsandscores")
persistentContainer.loadPersistentStores { (description, error) in
if let error = error {
fatalError("Core Data Store failed \(error.localizedDescription)")
}
}
}
func updateTeam() {
do {
try persistentContainer.viewContext.save()
} catch{
persistentContainer.viewContext.rollback()
}
}
func deleteTeam(team: Team){
persistentContainer.viewContext.delete(team)
do {
try persistentContainer.viewContext.save()
} catch{
persistentContainer.viewContext.rollback()
print("Failed to save context \(error)")
}
}
func getAllTeams() -> [Team] {
let fetchRequest: NSFetchRequest<Team> = Team.fetchRequest()
do{
return try persistentContainer.viewContext.fetch(fetchRequest)
}
catch {
return []
}
}
func saveTeams(player: String){
let teamCD = Team(context: persistentContainer.viewContext)
teamCD.player = player
do {
try persistentContainer.viewContext.save()
} catch {
print("failed to save team name \(error)")
}
}
}
let coreDM: CoreDataManager
#State private var playerHome : String = ""
#State private var allPlayersCIndex = 1
#State private var teams: [Team] = [Team]()
private func populateTeams(){
teams = coreDM.getAllTeams()
}
var body: some View{
VStack{
HStack{
TextField("NewPlayer", text: $playerHome )
.textFieldStyle(RoundedBorderTextFieldStyle())
Button("Save") {
coreDM.saveTeams(player: playerHome)
populateTeams()
playerHome = ""
}
}
List{
ForEach(teams, id: \.self) { name in
Text(name.player ?? "")
}
.onDelete(perform: { indexSet in
indexSet.forEach { index in
let team = teams[index]
coreDM.deleteTeam(team: team)
populateTeams()
}
})
}
///works fine:
Text("Number of players: \(teams.count) ")
///// I need help.
Text("Players Name: \(???????????[0]) ")
}
HStack{
///? Picker("Player", selection: $allPlayersCIndex,
content: {
ForEach(teams, id: \.self) { name in
///?? Text(name.player ?? "")
}
}
)
}

swiftui textfield is extremely laggy

I'm having issues where as more text is being typed into the textfield, the application (Mac) becomes more and more laggy.
class Action: ObservableObject, Identifiable {
var id = String(UUID().uuidString.prefix(7))
#Published var actionType = ActionType.display
#Published var arguments = [String:ValueType]()
}
struct AnalyticsKeyValuePairView: View {
var state: Action
let initialKey : String
#State var stateKey: String
#State var value: String
init(state: Action, initialKey: String) {
self.initialKey = initialKey
self.state = state
self._stateKey = State(initialValue: initialKey)
self._value = State(initialValue: state.arguments[initialKey]!.stringValue!)
}
var body: some View {
HStack {
TextField("key", text: $stateKey) { (b) in
} onCommit: {
if initialKey != stateKey {
state.setArgument(nil, forKey: initialKey)
}
state.setArgument(.string(value), forKey: stateKey)
}
Spacer()
TextField("value", text: $value) { (_) in
} onCommit: {
if initialKey != stateKey {
state.arguments[initialKey] = nil
}
state.setArgument(.string(value), forKey: stateKey)
}
}
}
in instruments you can see a lot core animation activity

Reset scroll SwiftUI List to top when reloaded with new data / MacOS

I have a List whose contents can be updated. If the contents are changed after the list has been scrolled down screen, the updated List does not reset to the top.
import SwiftUI
struct MyData {
let a: [String]
let b: [String]
init() {
var pa = [String]()
var pb = [String]()
for i in 0...100 {
pa.append("A: \(i)")
pb.append("B: \(i)")
}
self.a = pa
self.b = pb
}
}
struct ListNotResetingToTop: View {
let data = MyData()
#State var showA = true
var body: some View {
VStack {
Button("Switch") { showA.toggle() }
List(showA ? data.a : data.b, id: \.self) { value in
Text(value)
}
}
}
}
I've tried wrapping the List in a ScrollReader, but this did not work either:
struct ListNotResetingToTop: View {
let data = MyData()
#State var showA = true
var body: some View {
VStack {
Button("Switch") { showA.toggle() }
ScrollViewReader { proxy in
List(showA ? data.a : data.b, id: \.self) { value in
Text(value)
}.onChange(of: showA) { _ in
proxy.scrollTo(showA ? data.a.first : data.b.first)
}
}
}
}
}
Probably you need something like
VStack {
Button("Switch") { showA.toggle() }
List(showA ? data.a : data.b, id: \.self) { value in
Text(value)
}.id(showA) // just make id depend on modified data
}

SwiftUI Passing arguments over to View is not always available

I have a problem with passing arguments over to a View in SwiftUI when calling it. I have this View
import SwiftUI
struct GoodsItemFilterView: View {
#Environment(\.presentationMode) var presentationMode
#State var ref1Array: [String] = []
#State var ref2Array: [String] = []
#State var ref3Array: [String] = []
#State var stockStatusArray: [String] = []
#State var zoneArray: [String] = []
#State var selectorRef1 = 0
#State var selectorRef2 = 0
#State var selectorRef3 = 0
#State var selectorStockStatus = 0
#State var selectorZone = 0
var body: some View {
NavigationView {
Form{
Section(header: Text("Zone"), content: {
Picker(selection: $selectorZone, label:
Text("Zone")) {
ForEach(0 ..< zoneArray.count, id:\.self) {
Text(self.zoneArray[$0])
}
}
})
Section(header: Text("References"), content: {
Picker(selection: $selectorRef1, label:
Text("Reference 1")) {
ForEach(0 ..< ref1Array.count, id:\.self) {
Text(self.ref1Array[$0])
}
}
Picker(selection: $selectorRef2, label:
Text("Reference 2")) {
ForEach(0 ..< ref2Array.count, id:\.self) {
Text(self.ref2Array[$0])
}
}
Picker(selection: $selectorRef3, label:
Text("Reference 3")) {
ForEach(0 ..< ref3Array.count, id:\.self) {
Text(self.ref3Array[$0])
}
}
})
Section(header: Text("Status"), content: {
Picker(selection: $selectorStockStatus, label:
Text("Condition")) {
ForEach(0 ..< stockStatusArray.count, id:\.self) {
Text(self.stockStatusArray[$0])
}
}
})
Button(action: {
self.selectorZone = 0
self.selectorRef1 = 0
self.selectorRef2 = 0
self.selectorRef3 = 0
self.selectorStockStatus = 0
}, label: {
HStack(){
Spacer()
Image(systemName: "return")
Text("Reset filters")
Spacer()
}
})
}.navigationBarTitle("Filter")
.navigationBarItems(leading: (
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("Cancel")
}
)
), trailing: (
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("Done")
}
)
))
}.onAppear{
self.ref1Array.insert("***ALL***", at: 0)
self.ref2Array.insert("***ALL***", at: 0)
self.ref3Array.insert("***ALL***", at: 0)
self.stockStatusArray.insert("***ALL***", at: 0)
self.zoneArray.insert("***ALL***", at: 0)
}
}
}
struct GoodsItemFilter_Previews: PreviewProvider {
static var previews: some View {
GoodsItemFilterView(ref1Array: ["MAX100", "MAX101", "MAX102"], ref2Array: ["REF2_100", "REF2_101"], ref3Array: ["REF3_100", "REF3_101"])
}
}
and when I call it I can pass over the values of the arrays as arguments:
GoodsItemFilterView(ref1Array: ["MAX100", "MAX101", "MAX102"], ref2Array: ["REF2_100", "REF2_101"], ref3Array: ["REF3_100", "REF3_101"])
Now I have another view which is basically a copy of this one with a few changed names etc
//
// OrderHeaderFilter.swift
// WMS Toolbox
//
// Created by Max on 2020-01-24.
// Copyright © 2020 Max. All rights reserved.
//
import SwiftUI
//import Combine
struct OrderHeaderFilterView: View {
#Environment(\.presentationMode) var presentationMode
#State var orderTypeArray: [String] = []
#State var carrierArray: [String] = []
#State var fromStatus2 = UserDefaults.standard.string(forKey: "view.orderHeaderFilter.fromStatus")
// #State private var fromStatus2 = "040"
#State private var direction = ""
#State private var fromStatus = ""
#State private var toStatus = ""
#State private var orderType = ""
#State var selectorOrderType = 0
#State var selectorCarrier = 0
#State private var selectorIndex = 1
#State private var fromStatusSelectorIndex = 6
#State private var toStatusSelectorIndex = 2
#State private var directions = ["Inbound","Outbound","Both"]
private var orderStatusFromArray: [String] = ["005", "010", "022", "025", "030", "035", "040", "045", "046", "047", "060"]
private var orderStatusToArray: [String] = ["005", "010", "022", "025", "030", "035", "040", "045", "046", "047", "060"]
#State var orderStatus = OrderStatus.s05
enum OrderStatus: String, CaseIterable, Identifiable {
case s05 = "005"
case s10 = "010"
case s22 = "022"
case s25 = "025"
case s30 = "030"
case s35 = "035"
case s40 = "040"
case s45 = "045"
case s46 = "046"
case s60 = "060"
var id: String { rawValue }
}
enum Direction: String, CaseIterable{
case outbound = "1"
case inbound = "2"
case both = "3"
init(type: String) {
switch type {
case "1": self = .outbound
case "2": self = .inbound
case "3": self = .both
default: self = .both
}
}
var text: String {
switch self {
case .outbound: return "Outbound"
case .inbound: return "Inbound"
case .both: return "Both"
}
}
}
init(){
//nothing here
}
var body: some View {
return NavigationView{
Form{
HStack{
Text("Direction")
Spacer()
Picker(selection: $direction, label:
Text("Direction")) {
ForEach(directions, id:\.self) {
status in
Text(status)
}
}
.pickerStyle(SegmentedPickerStyle())
}
Picker(selection: $fromStatus, label:
Text("From Status")) {
ForEach(orderStatusFromArray, id:\.self) {
status in
Text(status)
}
}
Picker(selection: $toStatus, label:
Text("To Status")) {
ForEach(orderStatusFromArray, id:\.self) {
status in
Text(status)
}
}
}.navigationBarTitle("Filter")
.navigationBarItems(leading: (
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("Cancel")
}
)
), trailing: (
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("Done")
}
)
))
}.onAppear{
self.direction = UserDefaults.standard.string(forKey: "view.orderHeaderFilter.direction")!
self.fromStatus = UserDefaults.standard.string(forKey: "view.orderHeaderFilter.fromStatus")!
self.toStatus = UserDefaults.standard.string(forKey: "view.orderHeaderFilter.toStatus")!
self.orderTypeArray.insert("***ALL***", at: 0)
self.carrierArray.insert("***ALL***", at: 0)
}
}
}
struct OrderHeaderFilter_Previews: PreviewProvider {
static var previews: some View {
OrderHeaderFilterView()
}
}
and when I call it, it is not prompting me to pass over the arrays as arguments:
OrderHeaderFilterView()
What is the difference between those 2 views that the one is asking for arguments on initilization and the other one isn't? To be clear, in the end I want to pass over the arguments, so GoodsItemFilterView() is doing exactly what I need.
EnvironmentObjects are not passed via init method they are implicitly injected. The orderTypeArray and carrierArray have already initial values. So OrderHeaderFilterView() does not prompt you for arguments.
Found the issue(s):
I had this piece in the code
init(){
//nothing here
}
This needs to be removed, otherwise it will not ask for any variables.
The other issue is the one I don't understand:
private var orderStatusFromArray: [String] = ["005", "010", "022", "025", "030", "035", "040", "045", "046", "047", "060"]
private var orderStatusToArray: [String] = ["005", "010", "022", "025", "030", "035", "040", "045", "046", "047", "060"]
If I change the var to let, it works as expected. Another option is to remove the private at the beginning. So it looks like as soon as you have a
private var ...
in your code, all arguments become private. Maybe I am missing something here but that seems like a bug to me.

Resources