SwiftUI

[SwiftUI] 기본적인 UI 요소와 그 사용법 (1)

예빈 Yebeen 2024. 1. 12. 16:23
728x90
반응형

이번 시간에는 SwiftUI의 기본적인 UI 요소(Text, Image, Button, TextField)를 알아보고 직접 사용해보자 👩🏻‍🍳


Text

UIkit에서 UILabel이 사용된다면, SwiftUI에서는 Text가 그 역할을 해준다. 다만 차이점은 단순한 문자열 처리만 해주는게 아니라 버튼이나 다른 UI에 구성되는 텍스트를 모두 Text가 적용한다. UILabel 역할은 극히 일부라고 보면 될 듯!

 

Text Apple 공식 문서

 

Text | Apple Developer Documentation

A view that displays one or more lines of read-only text.

developer.apple.com

 

사용 방법

Text("텍스트 입력")

>> Text("Hello, Yecong's Code Recipe!")

 


Image

Image는 이미지 리소스, 아이콘 등을 화면에 뜨게 한다.색상과 크기 조절 등은 modifier로 변경할 수 있는데 이에 대한 상세한 설명은 추후 내용 학습 후 업로드할 예정!ㅎㅎ

 

Image Apple 공식 문서

 

Image | Apple Developer Documentation

A view that displays an image.

developer.apple.com

 

사용 방법

// MARK: - 이미지 리소스
Image("이미지 이름")

>> Image("code-recipe")

// MARK: - 아이콘
Image(systemName: "아이콘 이름")

>> Image(systemName: "circle.fill")

// MARK: - 도형

Rectangle()

Circle()

 


Button

버튼은 다양한 버튼이 있다. 기본 버튼부터 편집 버튼, 링크 버튼 등 다양한 버튼을 사용할 수 있다.

 

Button Apple 공식 문서

 

Button | Apple Developer Documentation

A control that initiates an action.

developer.apple.com

 

사용 방법

// MARK: -버튼 생성 방법
Button("버튼"){
     // 실행할 코드
 }
 
Button {
     // 실행할 코드
 } label: {
     Image(systemName: "circle.fill")
 }


// MARK: -EditButton
NavigationView {
     Text("Example")
         .navigationTitle("Buttons")
         .toolbar {
             EditButton()
         }
 }
 
 
// MARK: -Link
Link("링크 텍스트", destination: URL(string: "링크 첨부")!)
 
 
// MARK: -Menu
Menu("메뉴명"){
     Button("버튼1"){
         // 실행할 내용
     }
     Button("버튼2"){
         // 실행할 내용
     }
 }

 


TextField

TextField는 사용자로부터 텍스트를 입력받을 때 사용된다. placeholder와 바인딩을 인자로 받아 텍스트 필드를 생성한다.

 

TextField Apple 공식문서

 

TextField | Apple Developer Documentation

A control that displays an editable text interface.

developer.apple.com

 

사용 방법

// MARK: - TextEditor
@State var 변수 선언 필요

TextField("placeholder", text: $변수명)
	.textFieldStyle(스타일 변경)

 


SecureField

비밀번호와 같이 보안이 필요한 텍스트 입력 처리는 SecureField가 한다. 입력하는 텍스트를 별표나 원으로 표시되어 내용을 숨긴다.

 

SecureField Apple 공식 문서

 

SecureField | Apple Developer Documentation

A control into which the user securely enters private text.

developer.apple.com

사용 방법

// MARK: -SecureField 예시 코드
@State private var password = ""

SecureField("비밀번호 8자리를 입력하세요.", text: $password)

 


TextEditor

TextEditor는 사용자로부터 여러 줄의 텍스트 입력을 받는 데 사용된다. TextField와의 차이점은 TextField는 한 줄의 텍스트만 입력받고, TextEditor는 여러 줄의 텍스트를 입력받을 수 있다.

 

TextEditor Apple 공식 문서

 

TextEditor | Apple Developer Documentation

A view that can display and edit long-form text.

developer.apple.com

// MARK: -TextEditor 예시 코드

@State private var text = ""

TextEditor(text: $text)

 

다음 시간에는 남은 UI 요소(Slider, Toggle, Picker, Alert, ActionSheet)에 대해서 알아보기!

 

오늘의 코드 레시피👩🏻‍🍳 완료!🩷

728x90