๊ณต์๋ฌธ์ : A property wrapper type that can read and write a value that SwiftUI updates as the placement of focus within the scene changes.
์ฌ ๋ด ํฌ์ปค์ฑ ์์น๊ฐ ๋ณ๊ฒฝ๋จ์ ๋ฐ๋ผ SwiftUI๊ฐ ์ ๋ฐ์ดํธํ๋ ๊ฐ์ ์ฝ๊ณ ์ธ ์ ์๋๋ก ํด์ฃผ๋ ํ๋กํผํฐ ๋ํผ์ด๋ค.
@frozen @propertyWrapper
struct FocusState<Value> where Value : Hashable
iOS15๋ถํฐ ์ฌ์ฉ ๊ฐ๋ฅํ ํ๋กํผํฐ ๋ํผ์ด๋ค.
struct LoginForm: View {
enum Field: Hashable {
case username
case password
}
@State private var username = ""
@State private var password = ""
@FocusState private var focusedField: Field?
var body: some View {
Form {
TextField("Username", text: $username)
.focused($focusedField, equals: .username)
.onSubmit {
focusedField = .password
}
SecureField("Password", text: $password)
.focused($focusedField, equals: .password)
Button("Sign In") {
if username.isEmpty {
focusedField = .username
} else if password.isEmpty {
focusedField = .password
} else {
handleLogin(username, password)
}
}
}
}
}
์ ์ฝ๋์์ LoginForm ๋ทฐ๋ SwiftUI ๋ทฐ๋ก ์คํ ํ๋ฉด์ ๋ณธ๋ค๋ฉด ๋ก๊ทธ์ธ ํ๋ฉด์ ๋ ์ฌ๋ฆด ์ ์๋ค.
๊ฐ๋จํ ๋ก๊ทธ์ธ ํ๋ฉด์์ FocusState์ ์๋์ ํ์ธ ํ ์ ์๋ค.
.focused() modifier๋ฅผ ์ด์ฉํด ์ฌ์ ์ด์ ์์น๋ฅผ ํ์ธํ ์ ์์ผ๋ฉฐ Hashableํ ๊ฐ์ ํตํด์ ํด๋น ์์น๋ฅผ ์ง์ ํด ์ค ์๋ ์๋ค.
์ ์ฝ๋์์ username์ ์ ๋ ฅํ๋ ์ฐฝ์ด ์๊ณ , password๋ฅผ ์ ๋ ฅํ๋ ์ฐฝ์ด ์๋ค. Username์ ์ ๋ ฅ ์๋ฃํ๋ค๋ฉด focusedField๋ฅผ ์ด์ฉํด์ ๋น๋ฐ๋ฒํธ๋ฅผ ์ ๋ ฅํ๋ ํ ์คํธํ๋๋ก ๋ฐ๋ก ์ด๋์ด ๋๋ค.
๋ํ Sign In ๋ฒํผ์ ๋๋ ์ ๋, Username ํ ์คํธํ๋๊ฐ ๋น์ด์๋ค๋ฉด ๊ฑฐ๊ธฐ๋ก focus๊ฐ ์ด๋ํ๊ณ , Password ํ ์คํธ ํ๋๊ฐ ๋น์ด์๋ค๋ฉด ๊ฑฐ๊ธฐ๋ก ์ด๋ํ ๊ฒ์ด๋ค.