본문 바로가기

카테고리 없음

100DaysOfSwiftUI - Day 19

반응형

간단한 컨버터 어플리케이션을 만들라는 숙제.

제곱미터를 평으로, 평을 제곱미터로 변환하는 macOS  어플리케이션을 작성하 보았다.

막상 만들어보려니 간단한 TextField, Text, Picker 의 사용법도 헷갈렸다.

아주 무식한 코드는 다음과 같다.

import SwiftUI

struct ContentView: View {
    @State private var fromValue : Double = 0
    @State private var fromUnit = "제곱미터"
    @State private var toUnit = "평"
    
    @State private var toValue : Double = 0
    
    var toValue_ : Double {
        if fromUnit == toUnit {
            return fromValue
        }
        
        if fromUnit == "제곱미터" && toUnit == "평" {
            return fromValue * 121 / 400
        }
        
        if fromUnit == "평" && toUnit == "제곱미터" {
            return fromValue * 400 / 121
        }
        
        return 0
        
    }
    
    let units = [ "제곱미터", "평" ]
    
    var body: some View {
        
        Form {
            VStack {
                Section {
                    HStack{
                        TextField(" ", value: $fromValue, format: .number)
                        Picker(" ", selection: $fromUnit) {
                            ForEach(units, id: \.self) {
                                Text("\($0)")
                            }
                        }
                        .frame(width: 100.0)
                    }
                }
                
                Section {
                    HStack {
                        Spacer()
                            .frame(width: 15)
                        Text("\(toValue_)")
                        
                        Spacer()
                        
                        Picker(" ", selection: $toUnit) {
                            ForEach(units, id: \.self) {
                                Text("\($0)")
                                
                            }
                        }
                        .frame(width: 100.0)
                    }
                }
            }
            
        }
        .padding()
        .frame(width: 300)
        
    }
}

 

https://daewonyoon.tistory.com/440

 

 

 

728x90