[SwiftUI] List 선택

RudinP·2025년 7월 30일
0

Study

목록 보기
327/363

단일 선택

1. 선택을 저장할 @State 변수 생성

@State private var selected: AppleProduct? = nil

2. 리스트 내의 아이템을 선택할 수 있게 버튼으로 구현

List(items, selection: $selected) { item in
	Button {
		selected = item
	} label: {
		Text(item.name)
	}
}

바인딩 없이 구현해도 동일하다.

List(items) { item in
	Button {
		selected = item
	} label: {
		Text(item.name)
	}
}

다중 선택(편집 모드)

selection으로 선택을 바인딩하려면 리스트가 개별 항목을 선택할때의 바인딩(UUID)와 바인딩한 State variable 타입이 같아야 한다. 혹은 인스턴스 전체로 항목을 구분하게 하면 된다.

인스턴스 전체로 항목 구분하기

struct SingleSelection: View {
    var items = AppleProduct.sampleList
    
    @State private var selected: AppleProduct? = nil
        
    var body: some View {
        VStack {
            Text("Selected : \(selected?.name ?? "-")")
                .font(.largeTitle)
            
            List(items, id: \.self, selection: $selected) { item in
                Button {
                    //selected = item
                } label: {
                    Text(item.name)
                }
            }
        }
        .toolbar {
            EditButton()
        }
    }
}

  • 일반 선택 모드에서는 선택한 항목을 State 변수에 직접 저장. selection 파라미터 필요 X
  • 편집 모드에서는 selection 파라미터로 State 변수를 바인딩. List가 인스턴스를 구분할 때 사용하는 형식과 State 변수의 타입을 일치시켜야 한다.

다중 선택

iOS 16 이상부터는 EditMode가 아닌 경우 단일 선택이 기본으로 동작하고, selected에 선택한 항목이 저장된다.
따라서 EditMode가 아니어도 다중선택이 되길 원한다면 selected파라미터를 없애면 된다.

selected파라미터를 사용할 경우엔 EditMode에서 체크박스가 지원된다.

struct MultiSelection: View {
    var items = AppleProduct.sampleList
    
    @State private var selected: Set<AppleProduct> = []
    
    var body: some View {
        VStack {
            Text(" \(selected.count)item(s) selected")
                .font(.title)
            
            List(items, id: \.self) { item in
                Button {
                    if selected.contains(item) {
                        selected.remove(item)
                    } else {
                        selected.insert(item)
                    }
                } label: {
                    if selected.contains(item) {
                        Label("\(item.name)", systemImage: "checkmark")
                    } else {
                        Text(item.name)
                    }
                }
            }
        }
        .toolbar {
            #if os(iOS)
            EditButton()
            #endif
        }
    }
}
  • State 변수로 Set을 저장
  • 선택이 이미 되어있는 경우(Set에 포함된 경우) 삭제, 아닌 경우 추가
profile
iOS 개발자가 되기 위한 스터디룸...

0개의 댓글