- List 생성
@State var sampleList = ["sample1", "sample2", "sample3"]
var body: some View {
List {
ForEach(sampleList, id: \.self) { item in
Text(item)
}
}
}
- Section 추가
@State var sampleList = ["sample1", "sample2", "sample3"]
var body: some View {
List {
Section(header: Text("SampleList Header")) {
ForEach(sampleList, id: \.self) { item in
Text(item)
}
}
}
}
- List 아이템의 삭제 기능 추가
ForEach() 구문에 onDelete(perform:)으로 삭제 기능의 함수를 추가한다.
@State var sampleList = ["sample1", "sample2", "sample3"]
var body: some View {
List {
ForEach(sampleList, id: \.self) { item in
Text(item)
}
.onDelete(perform: delete)
}
}
func delete(indexSet: IndexSet) {
if let index = indexSet.first {
sampleList.remove(at: index)
}
}
- List 아이템의 순서 편집 기능 추가
NavigationView로 List를 감싸주고, navigationBarItems를 이용해 EditButton 을 만들고,
.onMove(perform:)으로 편집상태에 진입 했을 때 작동할 함수를 추가한다.
편집 상태에서 실행되는 함수의 동작을 구현한다.
@State var sampleList = ["sample1", "sample2", "sample3"]
var body: some View {
NavigationView {
List {
ForEach(sampleList, id: \.self) { item in
Text(item)
}
.onDelete(perform: delete)
.onMove(perform: move)
}
.navigationBarItems(trailing: EditButton())
}
}
func delete(indexSet: IndexSet) {
guard let index = indexSet.first else { return }
sampleList.remove(at: index)
}
func move(from source: IndexSet, to destination: Int) {
guard let source = source.first else { return }
let destination = destination >= sampleList.count ? sampleList.count - 1 : destination
sampleList.insert(sampleList.remove(at: source), at: destination)
}
'iOS > 기초' 카테고리의 다른 글
URLSession 사용하기 (0) | 2022.03.21 |
---|---|
[Swift] url로 ImageView에 image 설정하기 (0) | 2022.03.18 |
SwiftUI 기초 - State, onTabGesture, withAnimation (0) | 2020.09.25 |
SwiftUI 기초 - Slider, Stepper, Picker (0) | 2020.09.25 |
SwiftUI 기초 - Form (0) | 2020.09.25 |