struct TimeZoneView: View {
@State private var favorite = false
@State private var timezone: String = ""
private var timeZoneIdentifiers = TimeZone.knownTimeZoneIdentifiers
var body: some View {
ZStack {
Color.white
.ignoresSafeArea()
ScrollView(showsIndicators: false, content: {
VStack(spacing: 25) {
selection
Spacer()
}
})
}
}
}
Property “favourite" to select favorite country
Property timezone for transferring a country’s city name
timeZoneIdentifiers array of strings that is systemic for swiftui from which I get the country names
createSelection function for displaying and accepting data
func createSelection(
title: String,
clicked: (() -> Void)?,
favorite: Bool
) -> some View {
VStack {
Button(action: {
clicked?()
}, label: {
VStack(spacing: 10) {
VStack {
HStack {
Text(title)
.font(.custom(.semiBold, size: 16))
.foregroundColor(.theme.appBlack)
Spacer()
if favorite {
Image.app.addPurple
.resizable()
.frame(width: 16,height: 16)
}
}
.padding(20)
}
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.theme.grayProfileText, lineWidth: 0.5)
)
.padding([.leading,.trailing], 20)
}
})
}
}
“selection" to be displayed
ForEach that I do in the middle of “selection"
goes through the entire collection of country names
clicking on a selected country will trigger events such as assigning a timezone to the country’s city name and a toggle to select that country
var selection: some View {
VStack(spacing: 10) {
ForEach(timeZoneIdentifiers, id: \.self) { zone in
let temp = zone.components(separatedBy: "/")
if temp.count >= 2 {
let cityName = temp[1].replacingOccurrences(of: "_", with: " ")
createSelection(title: zone, clicked: {
timezone = cityName
favorite.toggle()
}, favorite: favorite)
}
}
}
}
The problem is that I can’t choose just one country selects all
>Solution :
A simple Bool
affects every cell, a better way is to keep the (selected) time zone in favorite
-
Declare
favorite
as emptyString
@State private var favorite = ""
-
Change the related (bound) types also to
String
. -
in
createSelection
replaceif favorite {
withif favorite == title {
. -
In
selection
replacefavorite.toggle()
withfavorite = zone
.