Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anatoliykant/7311c365d82bb7a1bd660767d13c60b7 to your computer and use it in GitHub Desktop.
Save anatoliykant/7311c365d82bb7a1bd660767d13c60b7 to your computer and use it in GitHub Desktop.
Movies list
import SwiftUI
struct MovieRecord: Codable {
let name: String
let starCount: Int
let date: Date
}
struct ContentView: View {
@AppStorage("movies_key") var savedMovies: String = "[]"
// @State var movies = [
// MovieRecord(name: "Avatar", starCount: 2, date: Date()),
// MovieRecord(name: "Titanic", starCount: 5, date: Date()),
// MovieRecord(name: "Terminator", starCount: 4, date: Date())
// ]
@State var isSheetOpened = false
var body: some View {
let movies = Binding<[MovieRecord]>(
get: { try! JSONDecoder().decode([MovieRecord].self, from: savedMovies.data(using: .utf8)!) },
set: { records in savedMovies = String(data: try! JSONEncoder().encode(records), encoding: .utf8)! }
)
NavigationView {
List {
ForEach(movies.wrappedValue, id: \.name) { movie in
HStack {
VStack(alignment: .leading) {
Text(movie.name)
HStack {
ForEach(1..<6) { i in
Image(systemName: i <= movie.starCount ? "star.fill" : "star")
.foregroundColor(.yellow)
}
}
}
Spacer()
Text(DateFormatter.normal.string(from: movie.date))
.scaledToFill()
}
.padding(8)
}
.onDelete { indexSet in
movies.wrappedValue.remove(atOffsets: indexSet)
}
}
.sheet(isPresented: $isSheetOpened, content: {
SheetView { name in
movies.wrappedValue.append(MovieRecord(name: name, starCount: 5, date: Date()))
isSheetOpened = false
}
})
.listStyle(InsetGroupedListStyle())
.navigationBarTitle(Text("Movies"))
.navigationBarItems(
trailing: Button {
isSheetOpened = true
} label: {
Image(systemName: "plus")
}
)
}
}
}
struct SheetView: View {
@State private var name: String = ""
@State var completion: (String) -> Void
var body: some View {
NavigationView {
TextField("Enter movie name", text: $name)
.padding()
.navigationBarItems(
trailing: Button {
completion(name)
} label: {
Text("Done")
.bold()
}
)
}
}
}
extension DateFormatter {
static var normal: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment