Skip to content

Instantly share code, notes, and snippets.

@azamsharp
Created January 17, 2021 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azamsharp/3723c8a5533263cc424563c3f1a7b7da to your computer and use it in GitHub Desktop.
Save azamsharp/3723c8a5533263cc424563c3f1a7b7da to your computer and use it in GitHub Desktop.
import SwiftUI
struct DetailView: View {
let customer: String
var body: some View {
Text(customer)
.font(.largeTitle)
}
}
struct ContentView: View {
let customers = ["Alex", "Mary", "John"]
@State var selectedCustomer: String?
var body: some View {
NavigationView {
VStack {
CustomerListView(customers: customers) { customer in
selectedCustomer = customer
print(customer)
}
Text("Just for Display")
CustomerListView(customers: customers)
if let selectedCustomer = selectedCustomer {
NavigationLink(
destination: DetailView(customer: selectedCustomer),
isActive: .constant(true),
label: {
EmptyView()
})
}
}
.onAppear(perform: {
selectedCustomer = nil
})
.navigationTitle("Customers")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
//
// CustomerListView.swift
// LearnSwiftUI
//
// Created by Mohammad Azam on 1/17/21.
//
import SwiftUI
struct CustomerListView: View {
let customers: [String]
let onSelected: ((String) -> Void)?
init(customers: [String], onSelected: ((String) -> Void)? = nil) {
self.customers = customers
self.onSelected = onSelected
}
var body: some View {
List(customers, id: \.self) { customer in
HStack {
Text(customer)
Spacer()
if onSelected != nil {
Image(systemName: "chevron.right")
}
}.contentShape(Rectangle())
.onTapGesture(perform: {
if let onSelected = onSelected {
onSelected(customer)
}
})
}.listStyle(PlainListStyle())
}
}
struct CustomerListView_Previews: PreviewProvider {
static var previews: some View {
CustomerListView(customers: ["John", "Alex", "Mary"])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment