I have the following lines of code for showing a list of friends.
import SwiftUI
struct ContentView: View {
@State var users = ["Susan", "Kate", "Natalie", "Kimberly", "Taylor", "Sarah", "Nancy", "Katherine", "Nicole", "Linda", "Jane", "Mary", "Olivia", "Barbara"]
@State var editMode = EditMode.inactive
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
}
.navigationBarTitle("Friends")
.environment(\.editMode, $editMode)
.navigationBarItems(leading: Button("Edit", action: {
if self.editMode == .active {
self.editMode = .inactive
} else {
self.editMode = .active
}
}))
}
}
}
If you see the code at the bottom, I have four lines just in order to change the value of editMode. Does SwiftUI have something like
showDetails.toggle()
where showDetails is a Boolean variable? Muchos thankos.
You can use toggle() on Bool, because Bool has a method named toggle():
As far as I checked, EditMode does not have a method named toggle() nor any other method of similar functionalities.
If you do want it, you can define your own extension for EditMode:
struct ContentView: View {
@State var users = ["Susan", "Kate", "Natalie", "Kimberly", "Taylor", "Sarah", "Nancy", "Katherine", "Nicole", "Linda", "Jane", "Mary", "Olivia", "Barbara"]
@State var editMode: EditMode = .inactive
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
}
.navigationBarTitle("Friends")
.environment(\.editMode, $editMode)
.navigationBarItems(leading: Button("Edit", action: {
self.editMode.toggle()
}))
}
}
}
extension EditMode {
mutating func toggle() {
if self.isEditing {
self = .inactive
} else {
self = .active
}
}
}