Created
March 17, 2021 13:10
-
-
Save nicnocquee/79300b01f89752b942ad85c7efe0bfc2 to your computer and use it in GitHub Desktop.
Swift Enumerations to SwiftUI list view
This file contains 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
struct EnumListView<Enum: RawRepresentable & | |
CaseIterable & | |
CustomStringConvertible> : View where | |
Enum.RawValue: Hashable, | |
Enum.AllCases: RandomAccessCollection { | |
var title: String = "" | |
@Binding var selectedItem: Enum? | |
var body: some View { | |
NavigationView { | |
List { | |
ForEach(Enum.allCases, id: \.rawValue) { (status) in | |
Button(action: { | |
selectedItem = Enum(rawValue: status.rawValue)! | |
}, label: { | |
HStack { | |
Text(status.description) | |
Spacer() | |
if selectedItem != nil && selectedItem! == status { | |
Image(systemName: "checkmark") | |
} | |
} | |
}) | |
} | |
} | |
.navigationBarTitle(LocalizedStringKey(title)) | |
} | |
} | |
} | |
struct EnumListView_Previews: PreviewProvider { | |
enum MugiwaraPirates: String, CaseIterable, CustomStringConvertible { | |
case luffy | |
case zoro | |
case sanji | |
case jinbei | |
case franky | |
case nami | |
case robin | |
case chopper | |
case brook | |
case usopp | |
var description: String { | |
return self.rawValue.capitalized | |
} | |
} | |
enum PiratesBounty: Int, CaseIterable, CustomStringConvertible { | |
case luffy = 1500000000 | |
case blackbeard = 2247600000 | |
case shanks = 4048900000 | |
case bigMom = 4388000000 | |
case kaido = 4611100000 | |
case whitebeard = 5046000000 | |
case roger = 5564800000 | |
var name: String { | |
switch self { | |
case .luffy: | |
return "Luffy" | |
case .blackbeard: | |
return "Blackbeard" | |
case .shanks: | |
return "Shanks" | |
case .bigMom: | |
return "Big Mom" | |
case .kaido: | |
return "Kaido" | |
case .whitebeard: | |
return "White Beard" | |
case .roger: | |
return "Gol D. Roger" | |
} | |
} | |
var description: String { | |
let formatter = NumberFormatter() | |
formatter.numberStyle = .decimal | |
let value = formatter.string(from: NSNumber(value: self.rawValue))! | |
return "\(self.name): \(value) Berries" | |
} | |
} | |
static var previews: some View { | |
Group { | |
EnumListView<PiratesBounty>(title: "Bounties", selectedItem: .constant(.luffy)) | |
EnumListView<MugiwaraPirates>(title: "Mugiwara Pirates", selectedItem: .constant(.luffy)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment