나의 발자취
[SwiftUI-UIKit] 같이 사용하기 본문
UIView를 SwiftUI 에서 쓰려면 UIViewRepresentable 프로토콜을 적용해주어야한다.
그리고 두 개의 함수가 필요하다.
view타입이니까 body가 필요없다.
some View를 UILabel로 바꾸어준다.
아래 함수에서 label을 넘겨받으려니, 위의 함수에 @Binding이 필요하다.
에러가 난다.
값을 넣어주어야한다.
binding되어있는 애들은 .constant로 해주면 에러가 해결된다.
바인딩 처리된 변수를 써줄땐 property wrapper인 $기호를 써준다.
makecoordinator
delegate로 동작하는 애들은 다 makecoordinator를 써주어야한다.
TableViewCoordinator.swift
import UIKit
class TableViewCoordinator: NSObject, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var config = cell.defaultContentConfiguration()
config.text = "\(indexPath.row)번째 row"
return cell
}
}
TableView.Swift
틀을 먼저 정해준다.
import SwiftUI
struct TableView: UIViewRepresentable {
func makeUIView(context: Context) -> UITableView {
<#code#>
}
func updateUIView(_ uiView: UITableView, context: Context) {
<#code#>
}
func makeCoordinator() -> TableViewCoordinator {
<#code#>
}
}
import SwiftUI
import UIKit
struct TableView: UIViewRepresentable {
func makeUIView(context: Context) -> UITableView {
// SwiftUI는 기본적으로 자기가 들어갈 공간이 정해져있으므로, 정해주지 않아도 됨.
let tableView = UITableView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.dataSource = context.coordinator
return tableView
}
func updateUIView(_ uiView: UITableView, context: Context) {
uiView.reloadData()
}
func makeCoordinator() -> TableViewCoordinator {
TableViewCoordinator()
}
class TableViewCoordinator: NSObject, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var config = cell.defaultContentConfiguration()
config.text = "\(indexPath.row)번째 row"
cell.contentConfiguration = config
return cell
}
}
}
#Preview {
TableView()
}
Coordinator
ObservableObject란?
ObservableObject는 객체가 변할 때 다른 부분에 알릴 수 있게 해주는 특별한 역할을 하는 프로토콜이다. 예를 들어, 날씨 정보를 담고 있는 WeatherProvider라는 클래스를 만들었을 때, 이 클래스에 있는 데이터가 바뀌면 그 변경 사항을 다른 곳에 알려줘야 할 때 ObservableObject를 사용한다.
즉, ObservableObject는 '이 객체가 변하면 알림을 보내주세요' 라는 규칙을 가진 객체
@Published란?
@Published는 클래스 안에서 데이터를 저장할 때 그 데이터가 바뀌었을 때, 바뀐 사실을 다른 곳에 알려주는 역할을 한다.
@Published를 붙인 변수는 언제든지 값이 바뀌면, 그 변화를 자동으로 알리고 화면을 다시 그려주는 역할을 한다. 이 기능은 주로 앱 화면을 만들 때 유용하게 쓰인다. 예를 들어, 날씨 정보가 바뀌면 화면에 표시된 날씨 정보도 자동으로 업데이트되게 만들 수 있다.
'앱 개발 > iOS' 카테고리의 다른 글
[SwiftUI ver] 당근마켓 거래서비스 풀스택 구현하기 (Frontend) - 로그인, 회원가입, 상품 리스트 업데이트 (1) | 2024.11.15 |
---|---|
[SwiftUI] OpenAPI 활용한 Book Finder App 만들기 (0) | 2024.11.08 |
FE] 당근마켓 아니고 양파마켓 만들기 (2) WIP (0) | 2024.11.07 |
[FE] 당근마켓 아니고 양파마켓 만들기 (!!!!!!WIP!!!!!!!) (0) | 2024.11.06 |
[UIKit] Alamofire, Azure AI Translate API 이용해서 간단 번역 기능 앱 만들기 (2) (3) | 2024.11.05 |