SwiftUI에서 사용자 입력 및 폼 다루기
SwiftUI는 사용자 입력 처리를 간단하고 직관적으로 만들기 위해 다양한 도구를 제공합니다. 이번 글에서는 텍스트 필드, 슬라이더, 토글, 선택기와 같은 기본 입력 컨트롤부터 복잡한 폼 구성까지 다루는 방법을 알아보겠습니다.
1. 기본 입력 컨트롤
텍스트 입력 (TextField)
사용자의 텍스트 입력을 처리하기 위해 TextField를 사용할 수 있습니다.
import SwiftUI
struct TextFieldExample: View {
@State private var name: String = ""
var body: some View {
VStack {
TextField("Enter your name", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Text("Hello, \(name)")
}
}
}
주요 포인트
- @State 속성 래퍼를 통해 입력 값을 바인딩합니다.
- textFieldStyle()을 활용하여 텍스트 필드의 스타일을 지정할 수 있습니다.
토글 (Toggle)
struct ToggleExample: View {
@State private var isOn: Bool = false
var body: some View {
Toggle("Enable feature", isOn: $isOn)
.padding()
}
}
슬라이더 (Slider)
struct SliderExample: View {
@State private var value: Double = 50
var body: some View {
VStack {
Slider(value: $value, in: 0...100)
Text("Value: \(value, specifier: "%.2f")")
}
.padding()
}
}
2. 폼 구성 (Form)
Form은 여러 입력 컨트롤을 그룹화하여 폼 레이아웃을 구성할 때 사용됩니다.
struct FormExample: View {
@State private var username: String = ""
@State private var notificationsEnabled: Bool = true
@State private var sliderValue: Double = 30
var body: some View {
Form {
Section(header: Text("User Info")) {
TextField("Username", text: $username)
Toggle("Enable Notifications", isOn: $notificationsEnabled)
}
Section(header: Text("Preferences")) {
Slider(value: $sliderValue, in: 0...100)
Text("Slider Value: \(sliderValue, specifier: "%.0f")")
}
}
}
}
주요 포인트
- Form과 Section을 활용해 입력 요소를 구조화합니다.
- 섹션 헤더나 푸터에 설명 텍스트를 추가할 수 있습니다.
3. 데이터 검증
입력된 데이터가 특정 조건을 만족하도록 검증하는 기능을 제공해야 할 때는 다음과 같은 패턴을 활용할 수 있습니다.
struct ValidationExample: View {
@State private var email: String = ""
@State private var errorMessage: String? = nil
var body: some View {
VStack {
TextField("Enter email", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.onChange(of: email) { newValue in
validateEmail(newValue)
}
if let errorMessage = errorMessage {
Text(errorMessage)
.foregroundColor(.red)
}
Button("Submit") {
if validateEmail(email) {
print("Email submitted: \(email)")
}
}
.padding()
}
}
func validateEmail(_ email: String) -> Bool {
if email.contains("@") {
errorMessage = nil
return true
} else {
errorMessage = "Invalid email address"
return false
}
}
}
주요 포인트
- onChange(of:)를 통해 실시간 입력 값을 검증합니다.
- 오류 메시지를 동적으로 표시합니다.
4. 결론
SwiftUI에서는 사용자 입력 및 폼 관리를 쉽게 수행할 수 있도록 다양한 도구를 제공합니다.
이러한 기능들을 조합하여 사용자 친화적인 입력 UI를 구성해 보시기 바랍니다.
'SwiftUI' 카테고리의 다른 글
SwiftUI 앱 퍼블리싱 및 배포 (0) | 2025.02.05 |
---|---|
SwiftUI와 Core Data 연동 (0) | 2025.02.05 |
SwiftUI에서 애니메이션과 트랜지션 다루기 (0) | 2025.02.05 |
SwiftUI에서의 네트워킹 및 데이터 처리 (0) | 2025.02.05 |
SwiftUI 데이터 바인딩과 상태 관리 (0) | 2025.02.05 |