Reputation: 59
I am enter value in TextField then i button click, after click i need change Text and put my result but my code not working, could you help me
Code:
import SwiftUI
struct ContentView: View {
@State var numeral: Double = 0.00
@State var result: Double = 0.00
var body: some View {
VStack{
TextField("Enrer numeral", value: self.$numeral, formatter: NumberFormatter())
.padding(20)
.frame(width: 300, height: 100)
.font(.largeTitle)
Text("\(result)")
.font(.largeTitle)
.padding()
Button(action: {
self.result = self.numeral*1.2
print(self.result)
print("sfsdfd")
}) {
Image(systemName: "play.fill")
.font(.largeTitle)
.foregroundColor(.red)
}
}
}
}
Upvotes: 0
Views: 2495
Reputation: 4875
It seems while using value:
as an input, SwiftUI does not reload the view.
SwiftUI reloads the view using text:
as an input whenever a key is pressed.
do it using below approach.
struct ContentView: View {
@State var numeral : String = "0.00"
@State var result: Double = 0.00
var body: some View {
VStack {
TextField("Enrer numeral", text: $numeral)
.keyboardType(.decimalPad)
.padding(20)
.frame(width: 300, height: 100)
.font(.largeTitle)
Text("\(result)")
.font(.largeTitle)
.padding()
Button(action: {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
if let val = Double(self.numeral) {
self.result = val * 1.2
print(self.numeral)
print(self.result)
}
else {
print("Entered value is invalid")
}
}) {
Image(systemName: "play.fill")
.font(.largeTitle)
.foregroundColor(.red)
}
}
}
}
Upvotes: 1
Reputation: 36181
A different approach, but this should work for you on ios devices and macos catalyst.
import SwiftUI
struct ContentView: View {
@State var numeral: Double = 0.00
@State var result: Double = 0.00
var body: some View {
VStack{
TextField("Enrer numeral", text: Binding<String>(
get: { String(format: "%.02f", self.numeral) },
set: {
if let value = NumberFormatter().number(from: $0) {
self.numeral = value.doubleValue
}}))
.padding(20)
.frame(width: 300, height: 100)
.font(.largeTitle)
Text("result \(result)")
.font(.largeTitle)
.padding()
Button(action: {
self.result = self.numeral * 1.2
print("---> result: \(self.result)")
// if you want to reset the TextField value
self.numeral = 0.00
}) {
Image(systemName: "play.fill")
.font(.largeTitle)
.foregroundColor(.red)
}
}
}
}
Upvotes: 0
Reputation: 257493
This should help
Button(action: {
// force textfield to commit
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),
to: nil, from: nil, for: nil)
self.result = self.numeral*1.2
print(self.result)
print("sfsdfd")
}
Upvotes: 0