본문 바로가기

학습 노트/Swift UI (2022)

(28)
33. AppStorage & SceneStorage AppStorage & SceneStorage AppStorarage와 SceneSotrage는 사용자의 선택사항을 저장한다. 둘을 사용하지 않고도 CoreData, Text file, Binary File을 사용해 구현하는 것도 가능하지만, 초기화 코드가 필요하고, 이를 위한 코드의 양이 만만치 않다. 따라서 SwiftUI에서는 OS가 제공하는 Default System이라는 기본 형식을 저장하는 기본 DB를 사용해 이를 간단히 해결할 수 있다. 이는 userDefaults로 Dictionary와 비슷하게 기능한다. AppStorage와 SceneStorage는 비슷하게 기능하지만. 이름대로 각각 App 전체와 특정 Scene에서 유효하다는 차이가 존재한다. @State private var numbe..
32. CoreData #2 CoreData #2 검색 기능 List { ForEach(members) { member in Button { editTarget = member } label: { HStack { Text(member.name!) .foregroundColor(.primary) Spacer() Text("\(member.age)") .foregroundColor(.secondary) } } } .onDelete(perform: delete(at:)) } .searchable(text: $keyword) .onChange(of: keyword, perform: { newValue in members.nsPredicate = newValue.isEmpty ? nil : NSPredicate(format: "name CO..
31. CoreData #1 CoreData #1 SwiftUI에서 CoreData를 사용해 CRUD를 구현해 본다. CoreData에는 MemberEntity가 존재하고, name과 age를 저장한다. SwiftUI에서 CoreData에 접근하는 방식은 UIKit에서 싱글톤 객체를 생성한 다음 mainContext에 접근하는 방식이 아닌, CoreData 자체를 공유 데이터로 설정해 각 View에서 접근하는 방식을 주로 사용한다. CoreData를 공유 데이터로 설정하기. @main struct DataPersistenceApp: App { let manager = CoreDataManager.shared var body: some Scene { WindowGroup { MainList() .environment(\.managed..
30. Gesture Tap Gesture .onTapGesture Apple Developer Documentation developer.apple.com struct TapGesture_Tutorials: View { @State private var tapCount = 0 var body: some View { VStack { Text("\(tapCount)") .font(.system(size: 250)) HStack { Image(systemName: "minus.circle") .font(.system(size: 100)) .foregroundColor(.red) .padding() .onTapGesture { tapCount -= 1 } Image(systemName: "plus.circle") .font(.sy..
29. List의 부가 기능 구현하기 List의 부가 기능 구현하기 Pull Refresh Apple Developer Documentation developer.apple.com 화면을 아래로 끌어당겨 새로고침 하는 iOS의 가장 보편적인 새로고침 방식이다. struct PullToRefresh: View { @State private var items = AppleProduct.sampleList[0 ..< 2] @State private var index = 2 var body: some View { List(items) { item in Text(item.name) } .animation(.easeInOut, value: items) .refreshable { await refresh() } } private func refresh(..
28. ForEach & Grid ForEach Apple Developer Documentation developer.apple.com struct View_ForEach: View { var items = AppleProduct.sampleList var body: some View { VStack { ForEach(items, id: \.name) { item in Text(item.name) } } } } 중간중간 등장했던 ForEach는 List나 이후에 살펴볼 Grid에서 폭넓게 사용된다. List와 마찬가지로 데이터를 나열한다는 점에서든 동일하지만, Table에 표시하지 않고 데이터들을 '나열' 하기만 한다. ForEach를 표시하는 형식은 ForEach가 어느 View에 Embed 됐는지가 기준이 됨을 기억하자. List의..
27. List #2 List #2 Selection Apple Developer Documentation developer.apple.com 일반 모드 struct SingleSelection: View { var items = AppleProduct.sampleList @State private var selected: AppleProduct? = nil var body: some View { VStack { Text("Selected item: \(selected?.name ?? "_")") List(items) { item in Button { selected = item } label: { Text(item.name) } } } } } 일반적인 List에 Selection 기능을 구현한 경우이다. 특별한 생성자의 사..
26. List #1 List #1 List는 여러 데이터를 각각의 열로써 수직으로 배치하는 View다. 애플의 모든 플랫폼을 지원하며, 각각에 알맞게 표시한다. SwiftUI의 List는 UIKit의 TableView와 같은 기능을 한다. StaticList struct StaticList: View { var body: some View { List { HStack { Text("Hello, World!") Text("Hello, World!") } Text("Hello, World!") Image(systemName: "star") Toggle(isOn: .constant(true)) { Text("On") } } } } List에 Embed 된 View를 각각의 개별 Cell로 구성한다. DynamicList stru..
25. StateObject @StateObject Apple Developer Documentation developer.apple.com struct StateObject_Tutorials: View { @State private var color: Color = Color.gray var body: some View { VStack { NumberView() .frame(width: 200, height: 200) .background(color) .clipShape(Circle()) Button { color = Color(white: Double.random(in: 0.5 ... 1.0), opacity: 1.0) } label: { Text("Change Color") } .padding() } } } 코드는 'Chang..
24. Observable Object & Environment Object Observable Object Apple Developer Documentation developer.apple.com ObservableObject는 ObservableObject, ObservedObject, Published 셋으로 이루어져 동작한다. Observable Object Class 프로토콜로 View에서 인스턴스의 변화를 감시 가능하다. 값이 바뀌면 View의 업데이트가 가능해진다. 주로 View 모델, 공유 데이터를 구성한다. Observed Object Property Wrapper이다. ObservableObject를 감시한다. Published Property Wrapper이다. ObservableObject에서 사용한다. 다른 View에서 해당 속성을 감시할 수 있다. cla..