새소식

iOS/SwiftUI

[SwiftUI] SwiftUI

  • -

SwiftUI


- 코드를 이용하여 UI를 구성

 

- Swift 파일에서 ContentView()를 사용

 

// Swift File
var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }

 

 

- Content View

//SwiftUI 지원 라이브러리 import
import SwiftUI

//View protocol : 화면이 보이는 요소
struct ContentView: View {
    //some 예약어 : View protocol을 준수하는 모든 View에 대한 Bool타입 허용
    var body: some View {
        Text("Hello, swiftUI!")
            .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

- body 부분

 var body: some View {
        Text("Hello, world!")
            .padding(.all, 30)
            .background(colorScheme == .light ? Color.white : Color.black)
            .foregroundColor(colorScheme == .light ? Color.black : Color.white)   
    }

 

  • padding : Content와 테두리 사이의 간격
    padding(.all) : 상하좌우 간격
  • background : 배경 색상

  • foregroundColor : 콘텐츠 색상

 

- View 생성

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group{
            ContentView()
            ContentView()  
        }
    }
}

→ Group에 Content 뷰 생성

 

 

- 원하는 Device를 뷰로 생성할 수 있음(아이폰 12, 아이폰 12프로맥스)

// 아이폰 12
    ContentView()
        .previewDevice(PreviewDevice(rawValue: "iPhone 12"))
        .previewDisplayName("iPhone 12")
// 아이폰 12 프로 맥스
    ContentView()
        .previewDevice(PreviewDevice(rawValue: "iPhone 12 Pro Max"))
        .previewDisplayName("iPhone 12 Pro Max")

 

 

 

- 다크모드 설정

- @Environment 레퍼런스로 변수 선언

struct ContentView: View {
    //Environment 속성 래퍼 : 환경설정을 읽어오는 어노테이션
    @Environment(\.colorScheme) var colorScheme
    
    var body: some View {
        Text("Hello, world!")
            .padding(.all, 30)
            .background(colorScheme == .light ? Color.white : Color.black)
            .foregroundColor(colorScheme == .light ? Color.black : Color.white)
    }
}

 

 

- 적용하기

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group{
            //기본모드 뷰
            ContentView()
                .environment(\.colorScheme, .light)
            //다크모드 뷰
            ContentView()
                .environment(\.colorScheme, .dark)
        }
    }
}

 

※ Simulator에 [설정] - [개발자]에서 다크 모드로 변경가능

 

 

 

 

참고

iOS 최신 앱 개발 강의 - 기초부터 핵심 요소, 간단한 포폴까지 제작(인프런)
https://www.inflearn.com/course/ios13-%EC%95%B1%EA%B0%9C%EB%B0%9C-%ED%8F%AC%ED%8F%B4

 

 

728x90

'iOS > SwiftUI' 카테고리의 다른 글

[SwiftUI] 공식문서 파헤치기 (2) [Stack]  (0) 2023.08.12
[SwiftUI] 공식문서 파헤치기 (1) [SwiftUI]  (0) 2023.08.05
[SwiftUI] Stack  (0) 2023.01.30
[SwiftUI] Image  (0) 2023.01.14
[SwiftUI] Text  (0) 2023.01.07
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.