안녕하세요. iOSangBong입니다.
저번 시간에는 FocusState에 대해 간단하게 알아봤는데요.
https://iosangbong.tistory.com/12
[iOS][SwiftUI] @FocusState 간단하게 알아보기
안녕하세요. iOSangBong입니다. 오늘은 FocusState에 대해 알아보겠습니다. 일단 공식 문서를 보게되면 https://developer.apple.com/documentation/swiftui/focusstate FocusState | Apple Developer Documentation A property wrapper type
iosangbong.tistory.com
오늘은 FocusState를 바인딩하는 방법에 대해 알아보겠습니다.
일단 바인딩 해줄자식뷰를 만들어 주겠습니다.
저번에 사용했던 클래스를 가져와서
하단에 이름 포커스 및 패스워드 포커스를 줄 수 있는 버튼을 만들었습니다.
간단하게 만들어주고 이제는 포커스를 바인딩 해주겠습니다.
이런식으로 focusField를 선언해준 다음 부모뷰에서 사용한 FocusEnum을 바인딩해줍니다.
버튼 액션 안에 wrappedValue를 이용해서 사용해주신 다음
자식뷰에 잊지말고 바인딩 시켜주면 된답니다~!
정말 쉬운데요 결과를 보게되면?
제대로 작동하시는 걸 볼 수 있습니다.
프로젝트를 진행하다보면 View를 따로 만들어서 사용해야될때가 있는데
유용하게 사용하셨으면 좋겠습니다.
참고를 위해 풀코드를 올려놓겠습니다~!
import SwiftUI
enum FocusEnum {
case name
case password
}
struct FocusView: View {
@State var nameText = ""
@State var passwordText = ""
@FocusState private var focusField: FocusEnum?
var body: some View {
VStack(spacing: 50) {
Group {
TextField("이름", text: $nameText)
.focused($focusField, equals: .name)
TextField("패스워드", text: $passwordText)
.focused($focusField, equals: .password)
}
.padding(.vertical, 7)
.padding(.horizontal, 10)
.background(
RoundedRectangle(cornerRadius: 4)
.strokeBorder(.black, lineWidth: 1)
)
HStack {
Group {
Button {
self.focusField = .name
} label: {
Text("이름")
.foregroundColor(.white)
}
Button {
self.focusField = .password
} label: {
Text("패스워드")
.foregroundColor(.white)
}
}
.frame(width: 150, height: 50)
.background(Color.blue)
}
Button {
self.focusField = nil
} label: {
Text("종료")
.foregroundColor(.white)
}
.frame(width: 150, height: 50)
.background(Color.blue)
FocusChildView(focusField: $focusField)
}
.padding()
}
}
struct FocusChildView: View {
var focusField: FocusState<FocusEnum?>.Binding
var body: some View {
HStack {
Button {
focusField.wrappedValue = .name
} label: {
Text("이름 포커스")
.foregroundColor(.white)
}
.frame(width: 150, height: 50)
.background(Color.orange)
Button {
focusField.wrappedValue = .password
} label: {
Text("패스워트 포커스")
.foregroundColor(.white)
}
.frame(width: 150, height: 50)
.background(Color.orange)
}
}
}
다들 즐코딩하세요. 그럼 이만~
'SwiftUI > 2. 잡기술' 카테고리의 다른 글
[iOS][SwiftUI] 키보드 간단하게 내리기 (0) | 2023.08.21 |
---|---|
[iOS][SwiftUI] Rectangle 특정 모서리 둥글게 만들기 (0) | 2023.08.07 |
[iOS][SwiftUI] safeArea 길이 구하기 (0) | 2023.07.25 |
[iOS][SwiftUI] Modal, fullScreenCover 배경 투명하게 만들기 (0) | 2023.07.15 |
[iOS][SwiftUI] Modal, fullScreenCover 애니메이션 없애기 (0) | 2023.07.13 |