swift ui 기초1 (변수, for, sort)

김부민·2021년 8월 31일
0

swift-ui

목록 보기
2/4

데이터 전달 및 사용방법

@State

  • 지역 변수로 주로 사용
  • private를 주로 붙임
  • 화면에서 값을 변경하는걸 허용 시킴
// 사용예시
@State private var str = “hello”

//값이 변경되지 않는 변수
private var str = “hello”

@Binding

  • 전달받은 값을 사용하고 싶을때
// 사용예시
@Binding var str: String

Observe

  • 계속 변경되는 값을 같이 사용하고 싶을때
  • Class 에서 사용가능
  • @ObservableObject : 관찰 가능한 객체
  • @ObservedObject : 관찰 된 객체
// Observe 사용예시 코드
class MyProfile: ObservableObject {
    @Published var name = "kim"
    @Published var age = 0
    
    func changeProfiel() {
        self.age = 30
        self.name = "min"
    }
}

struct ContentView: View {
    @ObservedObject var profile = MyProfile();
    
    var body: some View {
        VStack {
            Text("age \(self.profile.age)")
            Text("name \(self.profile.name)")
            
            Button(action: {
                self.profile.changeProfiel()
            }) {
                Text("Click me")
            }
        }
    }
}

Model 쓰는방법

선언

struct locationInfo: Hashable {
    var city = "";
    var weather = "";
}

ForEach에서 id 값을 self로 하기 위해선 Hashable을 같이 적용시켜줘야 한다.

배열선언시 사용

    @State private var locationArr = [
        locationInfo(city: "c1", weather: "w1"),
        locationInfo(city: "c2", weather: "w2"),
        locationInfo(city: "c3", weather: "w3")
    ];

ForEach 쓰는방법

                ForEach(locationArr, id: \.self) {
                    location in HStack {
                        Text("\(location.city)")
                        Text("\(location.weather)")
                    }
                }

각 생성되는 객체를 id 값을 기준으로 구별하기 때문에 id 값을 지정해 줘야 한다.


ForEach를 ID값 없이 사용하는방법

모델 선언부분

struct locationInfo: Identifiable {
    var id = UUID();
    
    var city = "";
    var weather = "";
}

Identifiable 를 같이 선언해주고, id 속성 값을 넣어준다.

위 코드에서 UUID() 함수는 난수 key값을 생성해주는 함수이다.

사용부분

                ForEach(locationArr) {
                    location in HStack {
                        Text("\(location.city)")
                        Text("\(location.weather)")
                    }
                }

ForEach를 for문처럼 쓰는 방법

1. for 숫자

// index 0,1,2,3,4
ForEach(0..<5) {
	index in
	Text("text \(index)")
}
// index 0,1,2,3,4,5
ForEach(0..5) {
	index in
	Text("text \(index)")
}

2. for 배열

ForEach(0..<locationArr.count) {
	index in
	Text("text\(locationArr[index].city)")
}

Sort

sort 사용예시)

.sorted(by: { $0.idx < $1.idx })

Swift에서는 첫번째 전달받는 값을 $0 으로 표시하고 그다음 전달받는 값은 $1으로 표시한다. $뒤에 그 다음 숫자를 계속 더한값을 표시한다.

전체코드)

//
//  ContentView.swift
//  swift-ui-learn
//
//  Created by 김부민 on 2021/08/27.
//

import SwiftUI

struct animal: Identifiable {
    var id = UUID();
    
    var name = "";
    var idx = 0;
}

struct ContentView: View {
    var animalArr = [
        animal(name: "dog", idx: 2),
        animal(name: "tiger", idx: 9),
        animal(name: "cat", idx: 6),
        animal(name: "bird", idx: 8),
        animal(name: "cat", idx: 4),
        animal(name: "dog", idx: 1),
        animal(name: "cat", idx: 5),
        animal(name: "bird", idx: 7),
        animal(name: "cat", idx: 3),
    ];
    
    var animalGroupd: [String: [animal]] {
        var group = Dictionary(grouping: animalArr) {
            $0.name
        }
        
        for(key,value) in group {
            group[key]=value.sorted(by: { $0.idx < $1.idx })
        }
        
        return group;
    }
    
    var groupKey: [String] {
        animalGroupd.map({ $0.key })
    }
    
    var body: some View {
        VStack(){
            List{
                ForEach(groupKey, id:\.self) {
                    key in
                    Section(header:Text("\(key)")) {
                        ForEach(animalGroupd[key]!) {
                            ani in
                            Text("\(ani.name) \(ani.idx)")
                        }
                    }
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
profile
froent-developer

0개의 댓글