점진적 과부하 개발 블로그

SwiftUI NavigationLink 활용 본문

Swift

SwiftUI NavigationLink 활용

지용빡 2022. 7. 1. 06:27
반응형
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를 작성을 안해도 간단한 코드로 값을 가져올 수 있습니다. 

반응형