Home > OS >  Conditionals, Variables, and Views
Conditionals, Variables, and Views

Time:10-14

New to Swift and having trouble finding the solution to this. It's probably a simple fix, that I haven't been able to figure out.

This program takes user input in a TextField and reacts based on that input (if input is a number, or not a number, and how many characters the input is).

I'm trying to figure out how to reassign the variable px within the conditional statements in order to vary font size.

Code below:

import SwiftUI

struct ContentView: View {
    
    @State var p: String = ""
    @State var px: Int = 35
    
    
    var body: some View {
        VStack(spacing: 0.0) {
            if p.isNotNum {
                if p.count > 10 {
                    px = 20 \\ this breaks
                }
                Text(String(p))
                    .font(.system(size: CGFloat(px)))
            } else if p.isNum {
                if p.count > 10 {
                    px = 20 \\ this breaks
                }
                Text(String(p))
            }
            TextField("P", text: $p)
        }
    }
}

extension String {
    var isNum: Bool {
        return Double(self) != nil
    }
}

extension String {
    var isNotNum: Bool {
        return Double(self) == nil
    }
}

CodePudding user response:

The body property is a view builder and system get new views as dependencies change ( here @State ) by calling this get {} property.

It's clear to use .onChange if you wanna do some changes based on @State property change .

struct ContentView: View {
    
    @State var p: String = ""
    @State var px: Int = 35
    
    
    var body: some View {
        VStack(spacing: 0.0) {
            if p.isNum {
                Text(String(p))
                    
            } else  {
                Text(String(p))
                    .font(.system(size: CGFloat(px)))
            }
            TextField("placeholder p ", text: $p)
        }
        .onChange(of: p, perform: { // <= here
            if $0.count > 10 {
                px = 20
            } else if p.count > 10 {
                px = 20
            }
        })
    }
}

CodePudding user response:

You can't use imperative code like px = 20 in the middle of your view hierarchy because it doesn't return a View

Use onChange instead:

.onChange(of: p, perform: {
    if $0.count > 10 {
        px = 20
    } else if p.count > 10 {
        px = 20
    }
})

Also, you can execute the code in some View by assigning a constant. For example:

let _ = { px = 20 }
  • Related