SwiftUI Picker Help -- Populating picker based on the selection of another picker - swift

I am trying to populate a picker based on the selection of another picker. I am new to Swift and have been beating my head on this for way too long. I am sure its not as difficult as I am making it but I would appreciate any assistance.
I think my biggest issue is passing the selection of the first picker to the array name of the second. I have used switch case, tried to pass the selection raw value...etc. Below is a sample of what I would like it to look like without the binding of the pickers. Thanks
import SwiftUI
struct veggie: View {
let veggies = ["Beans", "Corn", "Potatoes"]
let beanList = ["Pole", "String", "Black"]
let cornList = ["Peaches & Cream", "Sweet"]
let potatoList = ["Yukon Gold", "Idaho"]
#State private var selectedVeggie = "Bean"
#State private var selectedBean = "Pole"
#State private var selectedType = ""
var body: some View {
NavigationView{
VStack{
Form{
Picker("Please choose a veggie", selection: $selectedVeggie)
{
ForEach(veggies, id: \.self) {
Text($0)
}
}
Text("You selected \(selectedVeggie)")
Picker("Type", selection: $selectedBean)
{
ForEach(beanList, id: \.self) {
Text($0)
}
}
}
} .navigationTitle("Veggie Picker")
}
}
}

I'm imagining that you want this to be somewhat dynamic and not hardcoded with if statements. In order to accomplish that, I setup an enum with the veggie types and then a dictionary that maps the veggie types to their subtypes. Those look like:
enum VeggieType : String, CaseIterable {
case beans, corn, potatoes
}
let subTypes : [VeggieType: [String]] = [.beans: ["Pole", "String", "Black"],
.corn: ["Peaches & Cream", "Sweet"],
.potatoes: ["Yukon Gold", "Idaho"]]
Then, in the view, I did this:
struct ContentView: View {
#State private var selectedVeggie : VeggieType = .beans
#State private var selectedSubtype : String?
var subtypeList : [String] {
subTypes[selectedVeggie] ?? []
}
var body: some View {
NavigationView{
VStack{
Form{
Picker("Please choose a veggie", selection: $selectedVeggie)
{
ForEach(VeggieType.allCases, id: \.self) {
Text($0.rawValue.capitalized)
}
}
Text("You selected \(selectedVeggie.rawValue.capitalized)")
Picker("Type", selection: $selectedSubtype)
{
ForEach(subtypeList, id: \.self) {
Text($0).tag($0 as String?)
}
}
}
} .navigationTitle("Veggie Picker")
}
}
}
The selectedVeggie is now typed with VeggieType. The selectedSubtype is an optional String that doesn't have an initial value (although you could set one if you want).
The first picker goes through all of the cases of VeggieType. The second one dynamically changes based on the computed property subtypeList which grabs the item from the subTypes dictionary I had made earlier.
The tag item is important -- I had to make the tag as String? because SwiftUI wants the selection parameter and the tag() to match exactly.
Note: you say you're new to Swift, so I'll mention that you had named your view `veggie` -- in Swift, normally types have capital names. I named mine `ContentView`, but you could rename it `VeggieView` or something like that.

Related

Provide default value to properties in SwiftUI

I've learning SwiftUI for a week, recently I found a confusing issue with it.
#State private var checkAmount = 0.0
var body: some View {
NavigationView {
Form {
Section {
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
.keyboardType(.decimalPad)
}
Section{
Text(checkAmount, format:.currency(code: Locale.current.currency?.identifier ?? "USD"))
}
}
}
}
I use TextFile to receive user's input and alter the value of checkAmount, and make the value shown in the section below. Here is my preview in xcode.
Preview
But when I type a random number and delete it all, this happend:
Still a digit here
It seems SwiftUI didn't delete it all, and still keep the last digit I deleted.
I guess maybe I should give it an default value when user's input is empty?
Some additional information maybe necessary: I'm using a M1 MacMini and XCode 14.1
Approach
For currency(code:) the value type is Decimal, so you have to use Optional Decimal
https://developer.apple.com/documentation/foundation/parseableformatstyle/3796617-currency
When the last digit is deleted it becomes nil
Use checkAmount ?? 0 in your TextField
Code
struct ContentView: View {
#State private var checkAmount = Decimal?(0.0) //Optional decimal
var body: some View {
NavigationView {
Form {
Section {
TextField("Amount", value: $checkAmount, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
.keyboardType(.decimalPad)
}
Section{
//Use ?? operator to display 0 when nil
Text(checkAmount ?? 0, format:.currency(code: Locale.current.currency?.identifier ?? "USD"))
}
}
.onChange(of: checkAmount) { newValue in
print("checkAmount = \(String(describing: newValue))")
}
}
}
}

Swiftui navigation link to a qlpreview - property initialisers run before 'self' is available

Very new to coding and trying to teach myself swift. Running into a problem that I am having trouble understanding. Apologies if my code is a mess or my question is not clear.
I am creating a navigationview from a list I have created. I would like each list item to link to a detail page, that has a button opening a qlpreview of a word document, specific to that list item.
Firstly I have set the structure of my list items:
struct ScriptItem: Identifiable {
let id = UUID()
let ex: String
let phase: String
let doc: String
}
I then have my list and navigationview struct set up to link to a detailed view
struct ScriptsView: View {
#State private var queryString = ""
private let scriptList: [ScriptItem] = [
ScriptItem(ex: "101",
phase: "HMI",
doc: "PILOT NOTES EX 101"),
ScriptItem(ex: "102",
phase: "HMI",
doc: "PILOT NOTES EX 201")].sorted(by: {$0.ex < $1.ex})
var filteredScript: [ScriptItem] {
if queryString.isEmpty {
return scriptList
} else {
return scriptList.filter {
$0.ex.lowercased().contains(queryString.lowercased()) == true || $0.phase.lowercased().contains(queryString.lowercased()) == true
}
}
}
var body: some View {
NavigationView {
List(filteredScript) { scriptItem in
NavigationLink(destination: ScriptDetails(scriptitem: scriptItem)) {
HStack {
ZStack {
Text(scriptItem.ex)
}
Text(scriptItem.phase)
}
}
} .navigationBarTitle("Exercise Scripts")
} .searchable(text: $queryString, placement: .navigationBarDrawer(displayMode: .always), prompt: "Script Search")
}
}
My problem is in the next section - in the detail struct I'm trying to create a url link using forResource: but when I use the string from the previous struct I get the following error:
CANNOT USE INSTANCE MEMBER 'SCRIPTITEM' WITHIN PROPERTY INITIALIZER. PROPERTY INITIALIZERS RUN BEFORE 'SELF' IS AVAILABLE.
struct ScriptDetails: View {
let scriptitem: ScriptItem
let fileUrl = Bundle.main.url(
forResource: scriptitem.doc, withExtension: "docx"
)
ETC ETC ETC
Is there a way around this error that allows me to refer to the string I need from the previous struct?

How to update interface elements from asynchronous stuff from a singleton

I am developing my first app in SwiftUI and my brain have not wrapped around certain things yet.
I have to display prices, titles and descriptions of inapp purchases on the interface.
I have a singleton model like this, that loads as the app starts.
class Packages:ObservableObject {
enum Package:String, CaseIterable {
typealias RawValue = String
case package1 = "com.example.package1"
case package2 = "com.example.package2"
case package3 = "com.example.package3"
}
struct PurchasedItem {
var productID:String?
var localizedTitle:String = ""
var localizedDescription:String = ""
var localizedPrice:String = ""
}
static let sharedInstance = Packages()
#Published var purchasedItems:[PurchasedItem] = []
func getItem(_ productID:String) -> PurchasedItem? {
return status.filter( {$0.productID == productID } ).first
}
func getItemsAnync() {
// this will fill `purchasedItems` asynchronously
}
purchasedItems array will be filled with PurchasedItems, asynchronous, as the values of price, title and description come from the App Store.
Meanwhile, at another part of the interface, I am displaying buttons on a view, like this:
var buttonPackage1String:String {
let item = Packages.sharedInstance.getItem(Packages.Package.package1.rawValue)!
let string = """
\(umItem.localizedTitle) ( \(umItem.localizedPrice) ) \
\(umItem.localizedDescription) )
"""
return string
}
// inside var Body
Button(action: {
// purchase selected package
}) {
Text(buttonPackage1String)
.padding()
.background(Color.green)
.foregroundColor(.white)
.padding()
}
See my problem?
buttonPackage1String is built with title, description and price from an array called purchasedItems that is stored inside a singleton and that array is filled asynchronously, being initially empty.
So, at the time the view is displayed all values may be not retrieved yet but will, eventually.
Is there a way for the button is updated after the values are retrieved?
Calculable properties are not observed by SwiftUI. We have to introduce explicit state for this and update it once dependent dynamic data changed.
Something like,
#ObservedObject var packages: Packages
...
#State private var title: String = ""
...
Button(action: {
// purchase selected package
}) {
Text(title)
}
.onChange(of: packages.purchasedItems) { _ in
self.title = buttonPackage1String // << here !!
}
Below is a small pseudo code, I'm not sure it's suitable for your project but might give you some hint.
Packages.sharedInstance
.$purchasedItems //add $ to get the `Combine` Subject of variable
.compactMap { $0.firstWhere { $0.id == Packages.Package.package1.rawValue } } //Find the correct item and skip nil value
.map { "\($0.localizedTitle) ( \($0.localizedPrice) ) \ \($0.localizedDescription) )" }
.receive(on: RunLoop.main) // UI updates
.assign(to: \.buttonTitleString, on: self) //buttonTitleString is a #Published variable of your View model
.store(in: &cancellables) //Your cancellable collector
Combine framework knowledge is a must to start with SwiftUI.

How to build NumberField in SwiftUI?

I'm working on MacOS and I try to make NumberField — something like TextField, but for numbers. In rather big tree of views at the top I had:
...
VStack {
ForEach(instances.indices, id:\.self) {index in
TextField("",
text: Binding(
get: {"\(String(format: "%.1f", instances[index].values[valueIndex]))"},
set: {setValueForInstance(index, valueIndex, $0)})
)
}
}
...
And it worked well, but not nice:
✔︎ when I changed value, all View structure was redrawn – good
✔︎ values was updated if they were changed by another part of Views structure – good
✖︎ it was updated after each keypresses, which was annoying, when I tried to input 1.2, just after pressing 1 view was updated to 1.0. Possible to input every number but inconvenient – bad
So, I tried to build NumberField.
var format = "%.1f"
struct NumberField : View {
#Binding var number: Double {
didSet {
stringNumber = String(format: format, number)
}
}
#State var stringNumber: String
var body: some View {
TextField("" , text: $stringNumber, onCommit: {
print ("Commiting")
if let v = Double(stringNumber) {
number = v
} else {
stringNumber = String(format:format, number)
}
print ("\(stringNumber) , \(number)" )
})
}
init (number: Binding<Double>) {
self._number = number
self._stringNumber = State(wrappedValue: String(format:format, number.wrappedValue))
}
}
And It's called from the same place as before:
...
VStack {
ForEach(instances.indices, id:\.self) {index in
NumberField($instances[index].values[valueIndex])
}
}
...
But in this case it never updates NumberField View if values was changed by another part of View. Whats's wrong? Where is a trick?

Dynamic TextFields based on user input using SwiftUI

I am trying to create a dynamic set of TextFields which are added after the user presses the add button. Each press will add another set of those fields. I am new to this so please bear with me. I am getting a fatal error: index out of range. Here is a simple example of what I am trying to achieve.
struct ContentView: View {
#State var name: [String] = []
#State var counter = 0
var body: some View {
Form {
Section {
ForEach(0..<counter, id: \.self) { index in
TextField("Name", text: self.$name[index])
}
Button(action:{
self.counter += 1
}) {
Text("Add more")
}
}
}
}
}
You're increasing the counter without adding new items. If you add a new item to your array it will work without errors:
Button(action:{
self.name.append("")
self.counter += 1
}) {
Text("Add more")
}
But preferably don't use the counter variable at all. If you add a new item to the names array it's count will automatically increase. You can use it in the ForEach loop like this:
ForEach(0..<names.count, id: \.self) { index in
TextField("Name", text: self.$names[index])
}
Button(action:{
self.names.append("")
}) {
Text("Add more")
}
Note: For arrays it's better to use plural names: names instead of name. It indicates it's a collection of items.
SWIFTUI:
Here's the code to show multiple dynamic Text() element:
#State var textsArray = ["a","b","c","d"]
HStack{ ForEach(textsArray, id: \.self)
{ text in
Text("\(text)")
}
}
You can add more texts into "textsArray" or you can change the values in "textsArray" and it'll be automatically changing on UI.