Project Jo

Swift UI : Building Your First App 본문

Developer/Swift UI

Swift UI : Building Your First App

Project Jo 2020. 7. 27. 17:51

스위프트 UI 를 이제 차근히 공부해 보기로 하였다.

 

WWDC 강의를 참고하여 첫번째 앱을 만들어 본다.

URL : https://developer.apple.com/videos/play/wwdc2019/204

 

Introducing SwiftUI: Building Your First App - WWDC 2019 - Videos - Apple Developer

See SwiftUI in action! Watch as engineers from the SwiftUI team build a fully-functioning app from scratch. Understand the philosophy...

developer.apple.com

 

이후부터 작성하는 예제 프로젝트는 깃허브에도 추가되니 참고하면 좋다.

https://github.com/dongsuk1117/SwiftUI

 

dongsuk1117/SwiftUI

Swift UI study. Contribute to dongsuk1117/SwiftUI development by creating an account on GitHub.

github.com

 

WWDC 를 보며 완성한 프로젝트를 이곳에 첨부한다.

해당 첨부파일을 보면서 이 글을 참고하면 편하게 도움이 될것 같다.

Introducing SwiftUI_ Building Your First App.zip
1.09MB

 

WWDC 영상에서 천천히 알려주기 때문에 핵심적인 부분만 적어두려 한다. (기초적인건 'Swift UI 기초' 글을 참고 바란다.)

 

1. ObservedObject

위 예제에서 리스트를 표시하는 자료를 @ObservedObject 로 정의 되어 있다.

직역 하자면 관찰할 객체라는 뜻이고, 해당 객체에서 값이 변화하면 이벤트를 수신하고, 리스트를 갱신해줄 수 있다.

 

예제에서는 자료를 추가, 삭제, 이동시 해당 이벤트를 수신하여 리스트를 새롭게 갱신하도록 만들어져 있다.

이제 만드는법을 순서대로 적어본다.

 

1. ObservableObject 를 상속받는 클래스를 만들고 @Published 를 선언 및 PassthroughSubject 를 설정한다.

import SwiftUI
import Combine

class RoomStore: ObservableObject {
    @Published var rooms: [Room] {
        didSet { didChange.send() }
    }
    
    init(rooms: [Room] = []) {
        self.rooms = rooms
    }
    
    var didChange = PassthroughSubject<Void, Never> ()
}

 

2. @ObservedObject 를 선언하여 저장소를 설정하고, 해당 저장소에 값을 변경하면 리스트가 갱신된다.

struct ContentView: View {
    @ObservedObject var store = RoomStore()
    
    var body: some View {
        NavigationView {
            List {
                
                Section {
                    Button(action: addRoom, label: {
                        Text("Add Room")
                    })
                }
                
                Section {
                    ForEach (store.rooms) { room in
                        RoomCell(room: room)
                    }
                    .onDelete(perform: delete(at:))
                    .onMove(perform: move(from:to:))
                }
                
            }
            .navigationBarTitle("Rooms")
            .navigationBarItems(trailing: EditButton())
            .listStyle(GroupedListStyle())
        }
    }
    
    func addRoom() {
        store.rooms.append(Room(name: "Image5", capacity: 2000, hasVideo: false))
    }
    
    func delete(at offsets: IndexSet) {
        guard let index = Array(offsets).first else { return }
        store.rooms.remove(at: index)
    }
    
    func move(from source: IndexSet, to destination: Int) {
        store.rooms.move(fromOffsets: source, toOffset: destination)
    }
}

 

'Developer > Swift UI' 카테고리의 다른 글

Data Flow Through SwiftUI  (0) 2020.08.20
Swift UI 기초  (0) 2020.07.27