Tag: SwiftUI/BuildingListsAndNavigation
struct Landmark: Hashable, Codable { var id: Int var name: String var park: String var state: String var description: String }
struct Landmark: Hashable, Codable { var id: Int var name: String var park: String var state: String var description: String private var imageName: String var image: Image { Image(imageName) } }
struct Landmark: Hashable, Codable { var id: Int var name: String var park: String var state: String var description: String private var imageName: String var image: Image { Image(imageName) } private var coordinates: Coordinates var locationCoordinate: CLLocationCoordinate2D { CLLocationCoordinate2D( latitude: coordinates.latitude, longitude: coordinates.longitude) } struct Coordinates: Hashable, Codable { var latitude: Double var longitude: Double } }
var landmarks: [Landmark] = load("landmarkData.json") func load<T: Decodable>(_ filename: String) -> T { let data: Data guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find \(filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load \(filename) from main bundle:\n\(error)") } do { let decoder = JSONDecoder() return try decoder.decode(T.self, from: data) } catch { fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)") }
struct LandmarkRow: View { var landmark: Landmark var body: some View { HStack { landmark.image .resizable() .frame(width: 50, height: 50) Text(landmark.name) Spacer() } } } struct LandmarkRow_Previews: PreviewProvider { static var previews: some View { LandmarkRow(landmark: landmarks[0]); } }
struct LandmarkRow_Previews: PreviewProvider { static var previews: some View { LandmarkRow(landmark: landmarks[1]).previewLayout(.fixed(width: 300, height: 70)) } }
Group { LandmarkRow(landmark: landmarks[0]) .previewLayout(.fixed(width: 300, height: 70)) LandmarkRow(landmark: landmarks[1]) .previewLayout(.fixed(width: 300, height: 70)) }
リストビューを実装する。
struct LandmarkList: View { var body: some View { List { LandmarkRow(landmark: landmarks[0]) LandmarkRow(landmark: landmarks[1]) } } }
Listにコレクションを表示。
struct LandmarkList: View { var body: some View { List(landmarks, id: \.id) { landmark in LandmarkRow(landmark: landmark) } }