ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [SwiftUI] List와 ForEach 사용법
    SwiftUI 2024. 1. 17. 16:04
    728x90

    복잡한 UI 요소들을 한 번에 설명하기엔 너무 많은 양이 될 것 같아서 부분적으로 끊어서 학습하기로 한다. 오늘은 List와 ForEach의 사용법에 대해서 알아보자!👩🏻‍🍳


    List?

    List는 SwiftUI의 주요 구성 요소 중 하나로, 여러 행의 데이터를 표시하는데 사용된다. UIkit의 테이블 뷰와 유사하며, 각 행은 독립적인 View로 구성할 수 있다.

    List는 자체적으로 상태를 저장하지 않고 주어진 데이터를 기반으로 UI를 생성하고 업데이트한다. 항상 최신 상태의 데이터가 반영되도록 보장하며 데이터가 변경될 때마다 List는 자동으로 업데이트된다.

    List는 다양한 기능과 함께 사용될 수 있다. ForEach, Section, NavigationLink 등으로 복잡한 UI를 구성할 수 있다. 또한, ListStyle 속성을 사용하여 List의 스타일을 변경하거나, onPullToRefresh 기능을 통해 새로고침 기능을 추가할 수도 있다.

     

    List Apple 공식 문서

     

    List | Apple Developer Documentation

    A container that presents rows of data arranged in a single column, optionally providing the ability to select one or more members.

    developer.apple.com

     

    Multi Selection

     

    List에서는 사용자가 여러 항목을 동시에 선택할 수 있다. checkbox 버튼처럼 여러 항목을 선택할 수 있으며 아래 코드 처럼 간단하게 List를 구현해볼 수 있다.

     

    import SwiftUI
    
    struct Ingredient: Identifiable, Hashable {
        let name: String
        let id = UUID()
    }
    
    private var ingredients = [
        Ingredient(name: "Cabbage"),
        Ingredient(name: "Mushroom"),
        Ingredient(name: "Potato"),
        Ingredient(name: "Egg"),
        Ingredient(name: "Carrot"),
        Ingredient(name: "Garlic")
    ]
    
    struct ContentView: View {
    
        @State private var multiSelection = Set<UUID>()
        
        var body: some View {
            NavigationView {
                List(ingredients, selection: $multiSelection) {
                    Text($0.name)
                }
                .navigationTitle("재료 목록")
                .toolbar {EditButton()}
            }
            
            Text("\(multiSelection.count) selections")
        }
    }

     

     

    Section

    List에서는 Section을 사용하여 목록을 여러 섹션으로 나눌 수 있다.

     

    import SwiftUI
    
    struct ContentView: View {
        
        let data = ["Item 1", "Item 2", "Item 3"]
        
        var body: some View {
            List {
                Section(header: Text("Section 1")) {
                    ForEach(data, id: \.self) { item in
                        Text(item)
                    }
                }
                Section(header: Text("Section 1"), footer: Text("End of Section 1")) {
                    ForEach(data, id: \.self) { item in
                        Text(item)
                    }
                }
            }
        }
    }

     

     

    Hierarchical List

    List에서는 계층적인 데이터 구조를 표현할 수 있다. 

    import SwiftUI
    
    struct ContentView: View {
        
        struct FileItem: Hashable, Identifiable, CustomStringConvertible {
                var id: Self { self }
                var name: String
                var children: [FileItem]? = nil
                var description: String {
                    switch children {
                    case nil:
                        return "📄 \(name)"
                    case .some(let children):
                        return children.isEmpty ? "📂 \(name)" : "📁 \(name)"
                    }
                }
            }
            let fileHierarchyData: [FileItem] = [
              FileItem(name: "users", children:
                [FileItem(name: "user1234", children:
                  [FileItem(name: "Photos", children:
                    [FileItem(name: "photo001.jpg"),
                     FileItem(name: "photo002.jpg")]),
                   FileItem(name: "Movies", children:
                     [FileItem(name: "movie001.mp4")]),
                      FileItem(name: "Documents", children: [])
                  ]),
                 FileItem(name: "newuser", children:
                   [FileItem(name: "Documents", children: [])
                   ])
                ]),
                FileItem(name: "private", children: nil)
            ]
            var body: some View {
                List(fileHierarchyData, children: \.children) { item in
                    Text(item.description)
                }
            }
    }

     

    Refresh

    List에 새로고침 기능을 추가할 수 있다.

    struct ContentView: View {
        
        @State private var multiSelection = Set<UUID>()
        @State private var isLoading = false
        
        var body: some View {
            NavigationView {
                List(ingredients, selection: $multiSelection) {
                    Text($0.name)
                }
                .navigationTitle("재료 목록")
                .toolbar {
                    EditButton()
                }
                .refreshable {
                    await refreshData()
                }
            }
        }
        
        private func refreshData() async {
            isLoading = true
            
            await Task.sleep(2 * 1_000_000_000)
            
            isLoading = false
        }
    }

     

     

    List Style

    List에는 listStyle 모디파이어를 사용하여 리슽의 스타일을 변경할 수 있다. PlainListStyle, GroupedListStyle, InsetListStyle, SidebarListStyle 등의 스타일을 적용할 수 있다.

     

    - PlainListStyle

    - GroupedListStype

    - InsetGroupListStyle


    ForEach?

    ForEach는 컬렉션의 데이터를 기반으로 View를 생성할 수 있다. 이는 반복적인 UI 요소를 효율적으로 생성하는데 유용하며, 컬렉션의 항목이 변경되면 자동으로 View를 업데이트한다.

     

    ForEach Apple 공식 문서

     

    ForEach | Apple Developer Documentation

    A structure that computes views on demand from an underlying collection of identified data.

    developer.apple.com

     

    - List에 ForEach를 사용하는 이유

    List는 테이블 뷰와 유사한 역할을 하는 뷰이다. List 내부에 ForEach를 사용하면 동적인 목록을 만들 수 있다. 데이터의 각 항목에 대해 독립적인 행을 반복해서 생성할 수 있고, 데이터가 변경될 때마다 List가 자동으로 업데이트된다. 동적이고 반응형인 UI를 만드는데 아주 중요한 요소이다.

     


     

    오늘의 코드 레시피👩🏻‍🍳 완료!🩷

    728x90
예콩이의 코드 레시피