Last active
September 25, 2022 05:13
-
-
Save yasalmasri/d9f9565d27f23bcbf85733a434618eb4 to your computer and use it in GitHub Desktop.
Currency Field SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// CurrencyField | |
// | |
// Created by Yaser Almasri on 24/09/22. | |
// | |
import SwiftUI | |
struct ContentView: View { | |
@State private var amount: String = "12345" | |
var amountString: String { | |
if self.amount.isEmpty { | |
return currencyFormatter.string(from: NSNumber(value: Double(0)))! | |
} | |
let double = Double(self.amount)! / Double(100) | |
return currencyFormatter.string(from: NSNumber(value: double))! | |
} | |
var body: some View { | |
NavigationView { | |
VStack { | |
Text(self.amountString) | |
} | |
} | |
.overlay(alignment: .bottom, content: { | |
RoundedRectangle(cornerRadius: 10) | |
.fill(Color.black) | |
.frame(height: 250) | |
.overlay { | |
VStack { | |
HStack { | |
DigitBtn(text: 1, numberString: self.$amount) | |
DigitBtn(text: 2, numberString: self.$amount) | |
DigitBtn(text: 3, numberString: self.$amount) | |
} | |
HStack { | |
DigitBtn(text: 4, numberString: self.$amount) | |
DigitBtn(text: 5, numberString: self.$amount) | |
DigitBtn(text: 6, numberString: self.$amount) | |
} | |
HStack { | |
DigitBtn(text: 7, numberString: self.$amount) | |
DigitBtn(text: 8, numberString: self.$amount) | |
DigitBtn(text: 9, numberString: self.$amount) | |
} | |
HStack { | |
DigitBtn(text: 0, numberString: self.$amount) | |
Button { | |
self.amount = String(self.amount.dropLast()) | |
} label: { | |
Circle() | |
.fill(Color.gray) | |
.overlay { | |
HStack { | |
Image(systemName: "chevron.left") | |
.foregroundColor(.white) | |
} | |
} | |
} | |
} | |
} | |
} | |
}) | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
struct DigitBtn: View { | |
var text: Int | |
@Binding var numberString: String | |
var body: some View { | |
Button { | |
self.numberString = self.numberString.appending("\(text)") | |
} label: { | |
Rectangle() | |
.fill(Color.gray) | |
.overlay { | |
HStack { | |
Text("\(text)") | |
.foregroundColor(.white) | |
} | |
} | |
} | |
} | |
} | |
let currencyFormatter: NumberFormatter = { | |
let formatter = NumberFormatter() | |
formatter.locale = Locale.current | |
formatter.numberStyle = .currency | |
formatter.maximumFractionDigits = 2 | |
return formatter | |
}() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment