Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- array
- Observer
- singleton
- segue
- SWIFTUI
- uikit
- mvvm
- 회고
- list
- NotificationCenter
- class
- self
- 화면전환
- http
- IOS
- Refresh
- SWIFT
- escaping
- 글또
- apns
- viewlifecycle
- Switch
- struct
- error
- protocol
- 고차함수
- calendar
- Git
- ScrollView
- PushNotification
Archives
- Today
- Total
seong_hye, the developer
SwiftUI) List에 CheckBox 연동하기 본문
📘 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())
}
}
🔹결과
'IOS > SwiftUI' 카테고리의 다른 글
SwiftUI) 어플 자동 업데이트 기능에 대해 정리하기 (0) | 2024.03.27 |
---|---|
Swift) List 내용 삭제될 경우 기본 선택 값 변경되도록 제작하기 (0) | 2023.10.31 |
Swift) List 속 DropDown 사용하기 (0) | 2023.07.20 |
SwiftUI) Side Menu view에 대해 정리하기 (0) | 2022.12.06 |
Swift) Swift 스타일에 대해 알아보기 (0) | 2022.11.29 |
Comments