본문 바로가기
Language/Swift

SwiftUI를 이용한 목록 만들기 (List)

by IFLA 2022. 11. 9.

단일 열에 정렬된 데이터 행을 표시하는 컨테이너로, 선택적으로 하나 이상의 멤버를 선택할 수 있는 기능을 제공한다.

 

기본코드

var body: some View {
    List {
        Text("A List Item")
        Text("A Second List Item")
        Text("A Third List Item")
    }
}
  • 위의 예시는 정적 리스트다. List에 아이템을 하나씩 넣어준다.

 

실행화면


응용코드

import SwiftUI

struct Ocean: Identifiable {
    let name: String
    let id = UUID()
}

struct ContentView: View {
    private var oceans = [
        Ocean(name: "Pacific"),
        Ocean(name: "Atlantic"),
        Ocean(name: "Indian"),
        Ocean(name: "Southern"),
        Ocean(name: "Arctic")
    ]

    var body: some View {
        List(oceans) {
            Text($0.name)
        }
    }
}
  • 위의 예시는 동적 리스트다. 동적 리스트를 사용하기 위해선 Identifiable 프로토콜을 상속 받는 struct가 있어야 한다. Identifiable을 상속 받기 위해서는 고유 id 값만 있으면 된다.

 

실행화면


ListStyle 종류

  • DefaultListStyle() : 기본 리스트 스타일
  • GroupedListStyle() : 각 섹션을 분리된 그룹으로 묶어 표현
  • InsetGroupedListStyle()
  • PlainListStyle() : 데이터 목록을 각 행마다 하나씩 나열하는 형태의 기본 스타일
  • SidebarListStyle()

 

List의 메소드

  • .onDelete(perform: ) : row를 옮길 수 있다.
  • .onMove(perform: ) : 선택된 row를 삭제할 수 있다.
import SwiftUI

struct ContentView: View {
    @State var fruits = ["Apple", "banana", "Mango", "StrrawBery"]

    var body: some View {
        NavigationView {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit)
                }
                .onMove(perform: move)
            }
            .navigationBarItems(trailing: EditButton())
        }
    }

    func move(from source: IndexSet, to destination: Int) {
        let reversedSource = source.sorted()

        for index in reversedSource.reversed() {
            fruits.insert(fruits.remove(at: index), at: destination)
        }
    }
}

 

실행화면


개발자 Document

https://developer.apple.com/documentation/swiftui/list

댓글


\