반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- github
- RxSwift
- Firebase
- 문자열
- ios
- string
- SwiftLint
- remote config
- UIScrollView
- 웹뷰
- Android
- LazyHStack
- autolayout
- Alamofire
- Observable
- WebView
- Apple
- Realtime Database
- Java
- swipe
- subscript
- NavigationLink
- UITabBarController
- Swift
- gcd
- 라이트모드
- dictionary
- 다크모드
- UIButton
- SwiftUI
Archives
- Today
- Total
점진적 과부하 개발 블로그
SwiftUI NavigationLink 활용 본문
반응형
SwiftUI NavigationLink 활용
enum을 활용한 NavigationLink
- 여러가지 NavigationLink를 구성할때 일일이 NavigationLink를 구성하면 코드가 지저분해지기 떄문에 ForEach와 enum을 이용해서 간단한 코드로 구현을 해보겠습니다.
import Foundation
enum Menu: String, CaseIterable, Identifiable {
case service = "서비스"
case cs = "고객지원"
case terms = "약관 및 정책"
var title: String { rawValue }
var id: String { rawValue }
var menu: [String] {
switch self {
case .service: return Service.allCases.map { $0.title }
case .cs: return CS.allCases.map { $0.title }
case .terms: return Terms.allCases.map { $0.title }
}
}
enum Service: String, CaseIterable, Identifiable { // CaseIterable : enum을 자유자재로 Array 형태로 변형해 사용할 수 있다.
case frequency = "프리퀀시"
case reward = "리워드"
case coupon = "쿠폰"
case giftCard = "e-기프트카드"
case new = "What's New"
case notification = "알림"
case history = "히스토리"
case receipt = "전자영수증"
case myReview = "마이 스타벅스 리뷰"
var title: String { rawValue }
var id: String { rawValue }
}
enum CS: String, CaseIterable, Identifiable {
case storeCare = "스토어 케어"
case voiceOfCustomer = "고객의 소리"
case store = "매장 정보"
var title: String { rawValue }
var id: String { rawValue }
}
enum Terms: String, CaseIterable, Identifiable {
case terms = "이용약관"
case privacyTerms = "개인정보 처리 방침"
var title: String { rawValue }
var id: String { rawValue }
}
}
- 리스트를 보여줄 항목들의 enum을 정의하겠습니다.
- CaseIterable을 채택을하면 enum을 배열의 형태로 변환해 사용할 수 있습니다.
import SwiftUI
struct OtherView: View {
init() {
UITableView.appearance().backgroundColor = .systemBackground
}
var body: some View {
NavigationView {
List {
ForEach(Menu.allCases) { section in
Section(header: Text(section.title)) {
ForEach(section.menu, id: \.hashValue) { raw in
NavigationLink(raw,
destination: Text("\(raw)"))
}
}
}
}
.listStyle(GroupedListStyle())
.navigationTitle("Other")
.toolbar {
NavigationLink(
destination: SettingView(),
label: {
Image(systemName: "gear")
})
}
}
}
}
struct OtherView_Previews: PreviewProvider {
static var previews: some View {
OtherView()
}
}
- 그 다음 ForEach문을 이용해서 값을 가져옵니다. 그러면 일일히 NavigationLink를 작성을 안해도 간단한 코드로 값을 가져올 수 있습니다.
반응형
'Swift' 카테고리의 다른 글
SwiftLint 설치 방법 (0) | 2022.07.05 |
---|---|
SwiftLint 알아보기 (0) | 2022.07.04 |
Swift 한글이 포함된 url 처리하기 (0) | 2022.06.29 |
Swift Lazy Stored Properties (지연 저장된 프로퍼티) (0) | 2022.06.26 |
Swift 콜렉션 타입(Collection Types) (0) | 2022.06.23 |