seong_hye, the developer

SwiftUI) List에 CheckBox 연동하기 본문

IOS/SwiftUI

SwiftUI) List에 CheckBox 연동하기

seong_hye 2023. 9. 19.

 

📘 List와 CheckBox

List item에 그냥 checkBox를 넣게 되면 개별 계산이 안되는 경우가 있어서

개별로 활동가능한 경우를 정리해두려 작성


🔹Item 데이터 모델

struct Item: Identifiable {
	let id = UUID()
    let name: String
    var isChecked: Bool
}

 


🔹List에 적용

struct ContentView: View {
	 @State private var items: [Item] = [
        Item(name: "사과", isChecked: false),
        Item(name: "바나나", isChecked: false),
        Item(name: "오렌지", isChecked: false),
        Item(name: "포도", isChecked: false)
    ]
    // 선택된 item의 갯수 확인
    var selectedCount: Int {
        items.filter { $0.isChecked }.count
    }
	// 전체 선택
    var allSelected: Bool {
        items.allSatisfy { $0.isChecked }
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text("선택된 항목: \(selectedCount)개")
                    .font(.headline)
                
                Spacer()
                
                Button(action: {
                    // 전체 선택 or 전체 해제
                    let newValue = !allSelected
                    for index in items.indices {
                        items[index].isChecked = newValue
                    }
                }) {
                    Text(allSelected ? "전체 해제" : "전체 선택")
                        .font(.subheadline)
                        .padding(6)
                        .background(Color.blue.opacity(0.2))
                        .cornerRadius(8)
                }
            }
            .padding([.horizontal, .top])

            List {
                ForEach(items.indices, id: \.self) { index in
                    Toggle(isOn: $items[index].isChecked) {
                        Text(items[index].name)
                    }
                    .toggleStyle(CheckboxToggleStyle())
                }
            }
        }
    }
}

 

➡️ CheckBox 스타일 정리

// 사용자 정의 체크박스 스타일
struct CheckboxToggleStyle: ToggleStyle {
    func makeBody(configuration: Configuration) -> some View {
        Button(action: {
            configuration.isOn.toggle()
        }) {
            HStack {
                Image(systemName: configuration.isOn ? "checkmark.square" : "square")
                    .foregroundColor(configuration.isOn ? .blue : .gray)
                configuration.label
            }
        }
        .buttonStyle(PlainButtonStyle())
    }
}

🔹결과


 

Comments