// ContentView.swift
import SwiftUI
struct ContentView: View {
// This gets the first card where the name property is "Card1"
@ObservedObject private var card: Card = cards.first(where: { $0.name == "Card1" }) ?? Card.emptyCard
var body: some View {
VStack {
// In order to reduce duplicated code, I moved the TextField and related stuff into its own View struct
CoordEntryView(isLatitude: true, card: card)
Divider()
CoordEntryView(isLatitude: false, card: card)
}
.padding()
}
}
struct CoordEntryView: View {
var isLatitude: Bool // Allows us to use this same code for the two different coorindates
@ObservedObject var card: Card
@State private var valueOk: Bool = true
var body: some View {
Text(isLatitude ? "Latitude" : "Longitude")
.bold()
TextField("Enter value", text: (isLatitude ? $card.coord.latitude : $card.coord.longitude))
.multilineTextAlignment(.center)
.font(.system(size: 36))
.frame(maxWidth: 300)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(Color.blue.opacity(0.15))
)
.onAppear(perform: {
checkCoords()
})
.onChange(of: (isLatitude ? card.coord.latitude : card.coord.longitude)) {
checkCoords()
}
if(!valueOk) {
Text(Coordinate.formatIncorrect)
.foregroundStyle(.red)
}
}
private func checkCoords() {
// Checks the coordinate value is valid, removes irrelevant characters, makes sure the minus sign is at the beginning, and trims to the right length
if(isLatitude) {
valueOk = (card.coord.latitude.wholeMatch(of: /^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/) != nil)
card.coord.latitude = Coordinate.validate(card.coord.latitude)
// Trim to the right length
card.coord.latitude = String(card.coord.latitude.prefix((card.coord.latitude.prefix(1) == "-" ? 10 : 9)))
} else {
valueOk = (card.coord.longitude.wholeMatch(of: /^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/) != nil)
card.coord.longitude = Coordinate.validate(card.coord.longitude)
// Trim to the right length
card.coord.longitude = String(card.coord.longitude.prefix((card.coord.longitude.prefix(1) == "-" ? 11 : 10)))
}
}
}
#Preview {
ContentView()
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: