Ricky Chhetri
Ricky Chhetri

Reputation: 91

Not able to clear TextField

When I enter the number both on a and b, suppose 58 and 78 in the text field. And then when I go back to clear the number a, and come to number b, the number a value shows up with 5 instead of 0, is there anyway I can get this fixed to show a 0 value when the number is cleared instead of showing 5? Here's is the code.

import SwiftUI

struct ContentView: View {
    @State var a = Double()
    @State var b = Double()

    var body: some View {
        HStack {
            Text("Number 1")
            TextField("Enter Number 1", value: $a, format: .percent)
        }
        HStack {
            Text("Number 2")
            TextField("Enter Number 2", value: $b, format: .percent)
        }
    }
}

Upvotes: 1

Views: 964

Answers (2)

Steven-Carrot
Steven-Carrot

Reputation: 3051

You can try this way.

struct ContentView: View {

@State var a: Double?
@State var b: Double?
@State var result : Double = 0.0

var body: some View {
    HStack {
        Text("Number 1")
        TextField("Enter Number 1", value: $a, format: .percent)
       
    }
    HStack {
        Text("Number 2")
        TextField("Enter Number 2", value: $b, format: .percent)
    }
    HStack {
        Button  {
            result = (a ?? 0.0) * (b ?? 0.0)
        } label: {
            Text("calculate a * b")
        }
        Text("\(result)")
    }
}
}

Upvotes: 0

Vadim Belyaev
Vadim Belyaev

Reputation: 2859

The values bound to the text field have the type Double and they can't ever be empty.

Here's what happens:

  1. You type "58" into the text field. The binding from the text field to the state var updates its value to 58.0.
  2. You erase the 8, the value of the text field becomes "5" and the state var gets updated with the new value of 5.0.
  3. You erase the remaining digit of 5, the value of the text field becomes nil. SwiftUI tries updating the state var with the value of nil, but it can't because its type is Double, so the state var keeps the previous value of 5.0.
  4. You move the focus to the next text field. SwiftUI re-renders the views and the first text field gets updated with the value of its bound state var, which is 5.

To fix it, change the type of the state vars to optional:

@State var a: Double?
@State var b: Double?

Upvotes: 1

Related Questions