UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 24: Views and modifiers: Wrap up - First Challenge

Forums > 100 Days of SwiftUI

@ian  

I was working on the first challenge listed here: https://www.hackingwithswift.com/books/ios-swiftui/views-and-modifiers-wrap-up

"Go back to project 1 and use a conditional modifier to change the total amount text view to red if the user selects a 0% tip."

I was able to make it work using .onChange but feel like this might not have been the correct approach and I am missing a simpler way to do this.

Below is my code:

//
//  ContentView.swift
//  WeSplit
//
//  Created by user on 10/17/22.
//

import SwiftUI

struct ContentView: View {

    @State private var checkAmount = 0.0
    @State private var numberOfPeople = 2
    @State private var tipPercentage  = 20

    @FocusState private var amountIsFocused: Bool

    @State private var noTipRude = false

    var localCurrency: FloatingPointFormatStyle<Double>.Currency {
        return .currency(code: Locale.current.currency?.identifier ?? "USD")
    }

    var grandTotal: Double {
        let peopleCount = Double(numberOfPeople + 2)

        let tipSelection = Double(tipPercentage)

        let tipValue = checkAmount / 100 * tipSelection

        let grandTotal = checkAmount + tipValue

        return grandTotal
    }

    var totalPerPerson: Double {
        let peopleCount = Double(numberOfPeople + 2)
        let tipSelection = Double(tipPercentage)

        let tipValue = checkAmount / 100 * tipSelection

        let grandTotal = checkAmount + tipValue

        let amountPerPerson = grandTotal / peopleCount

        return amountPerPerson
    }

    var body: some View {
        NavigationView {

            Form {

                Section {
                    TextField("Amount", value: $checkAmount, format: localCurrency) //.currency(code: Locale.current.currency?.identifier ?? "USD"))
                        .keyboardType(.decimalPad)
                        .focused($amountIsFocused)

                    Picker("Number of People", selection: $numberOfPeople) {
                        ForEach(2..<100){
                            Text("\($0) people")
                        }
                    }

                }

                Section {
                    Picker("Tip percentage", selection: $tipPercentage) {
                        //ForEach(tipPercentages, id: \.self) {
                        ForEach( 0..<101 ) {
                            Text($0, format: .percent)

                        }
                    }.onChange(of: tipPercentage) { _ in
                        if tipPercentage == 0 {
                            noTipRude = true
                        } else
                        {
                            noTipRude = false
                        }

                    }

                } header: {
                    Text("How much tip do you want to leave?")
                }

                Section {
                    Text(grandTotal, format: localCurrency) //.currency(code: Locale.current.currency?.identifier ?? "USD"))
                        .foregroundColor(noTipRude ? .red : .black)

                } header: {
                    Text("Grand Total:")
                }

                Section {
                    Text(totalPerPerson, format: localCurrency) //.currency(code: Locale.current.currency?.identifier ?? "USD"))
                } header: {
                    Text("Amount per person:")
                }
            }

            .navigationTitle("WeSplit")
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    Button("Done") {
                        amountIsFocused = false
                    }
                }
            }
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2      

Ian has a doubt about his approach:

I was able to make it work using .onChange
but feel like this might not have been the correct approach
and I am missing a simpler way to do this.

Well done. It's great you're taking a critical look at your solution and asking questions.

@twoStraws challened you to apply a conditional modifier. I think you applied procedural logic, instead.

Remember! SwiftUI is a declarative language. You should think about DECLARING what you want your user to see. In this case, make a declaration:

Make the box green when the user left a tip. Otherwise, make it red.

In a procedural language you might add conditionals:

IF the tip is ZERO, then display THIS VIEW.
If the tip is GREATER than zero, then display ANOTHER VIEW.

// Paste this into Playgrounds
import PlaygroundSupport
struct TipView: View {
    @State private var theTip = 0.00

    // Computed variable.
    // Did the patron leave a tip? Return TRUE or FALSE
    var leftATip: Bool { theTip > 0.00 }

    var body: some View {
        ZStack {
            // SwiftUI is declarative.
            // DECLARE what you want the user to see.
            Rectangle().foregroundColor( leftATip ? .green : .red)  // Declare the color based on the TIP value
            Text(totalTip).font(.largeTitle).padding(.horizontal)
        }
        // Change the value on each tap.
        .onTapGesture {
            theTip = leftATip ? 0.00 : Double.random(in: 5.0...9.0) // Tap to change the tip.
        }
    }

    // Format as a currency string.
    var totalTip: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        return formatter.string(from: NSNumber(value: theTip)) ?? "$0"
    }
}

// Run this line in Playgrounds. Tap the rectangle.
PlaygroundPage.current.setLiveView(TipView())

2      

@ian  

Thanks, I knew it should be something like that just couldn't put my head around how to do it.

For anyone else looking your playground example also needs toimport SwiftUI or at least I did.

//
//  ContentView.swift
//  WeSplit
//
//  Created by user on 10/17/22.
//

import SwiftUI

struct ContentView: View {

    @State private var checkAmount = 0.0
    @State private var numberOfPeople = 2
    @State private var tipPercentage  = 20

    @FocusState private var amountIsFocused: Bool

    //If tipPercentage picker value is greater than 0 then a TRUE a tip was left else false no tip was left
    var noTipRude: Bool { tipPercentage > 0}

    var localCurrency: FloatingPointFormatStyle<Double>.Currency {
        return .currency(code: Locale.current.currency?.identifier ?? "USD")
    }

    var grandTotal: Double {
        let peopleCount = Double(numberOfPeople + 2)

        let tipSelection = Double(tipPercentage)

        let tipValue = checkAmount / 100 * tipSelection

        let grandTotal = checkAmount + tipValue

        return grandTotal
    }

    var totalPerPerson: Double {
        let peopleCount = Double(numberOfPeople + 2)
        let tipSelection = Double(tipPercentage)

        let tipValue = checkAmount / 100 * tipSelection

        let grandTotal = checkAmount + tipValue

        let amountPerPerson = grandTotal / peopleCount

        return amountPerPerson
    }

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Amount", value: $checkAmount, format: localCurrency) //.currency(code: Locale.current.currency?.identifier ?? "USD"))
                        .keyboardType(.decimalPad)
                        .focused($amountIsFocused)

                    Picker("Number of People", selection: $numberOfPeople) {
                        ForEach(2..<100){
                            Text("\($0) people")
                        }
                    }
                }

                Section {
                    Picker("Tip percentage", selection: $tipPercentage) {
                        //ForEach(tipPercentages, id: \.self) {
                        ForEach( 0..<101 ) {
                            Text($0, format: .percent)
                        }
                    }
                } header: {
                    Text("How much tip do you want to leave?")
                }

                Section {
                    Text(grandTotal, format: localCurrency) //.currency(code: Locale.current.currency?.identifier ?? "USD"))
                        .foregroundColor(noTipRude ? .black : .red)

                } header: {
                    Text("Grand Total:")
                }

                Section {
                    Text(totalPerPerson, format: localCurrency) //.currency(code: Locale.current.currency?.identifier ?? "USD"))
                } header: {
                    Text("Amount per person:")
                }
            }

            .navigationTitle("WeSplit")
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    Button("Done") {
                        amountIsFocused = false
                    }
                }
            }
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.