티스토리 뷰

iOS 개발/SwiftUI

SwiftUI) List 개념 예제

iDrogba 2022. 1. 23. 16:59

예제 코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 
import SwiftUI
 
struct Animal: Identifiable{
    let id = UUID()
    let name: String
    let index: Int
}
 
struct ContentView: View {
    
    var animalList = [
        Animal(name: "dog", index: 3),
        Animal(name: "dog", index: 1),
        Animal(name: "dog", index: 2),
        Animal(name: "cat", index: 7),
        Animal(name: "cat", index: 5),
        Animal(name: "bird", index: 4),
        Animal(name: "bird", index: 6)
    ]
    
    var animalDictionary: [String:[Animal]]{
        var dictionaryData = Dictionary(grouping: animalList){ $0.name }
        for (key,value) in dictionaryData {
            dictionaryData[key] = value.sorted(by: {
                $0.index < $1.index
            })
        }
        return dictionaryData
    }
    
    var animalDictionaryKeys: [String] {
        animalDictionary.map( { $0.key } )
    }
    
    var body: some View {
        
        List{
            ForEach(animalDictionaryKeys, id: \.self){ key in
                Section(header: Text("\(key)")){
                    ForEach(animalDictionary[key]!){ animal in
                        HStack{
                        Text("\(animal.name)")
                        Text("\(animal.index)")
                        Text("\(animal.id)")
                        }
                    }
                }
            }
        }
    }
}
 
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
        }
    }
}
 
cs

 

실행 결과

 

학습 개념

struct Animal : UUID(), identifiable

animalDictionary : sort

List : ForEach 구문, closer 활용, Section 활용

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함