Skip to content

Latest commit

ย 

History

History
63 lines (49 loc) ยท 2.25 KB

FocusState.md

File metadata and controls

63 lines (49 loc) ยท 2.25 KB

FocusState

๊ณต์‹๋ฌธ์„œ : A property wrapper type that can read and write a value that SwiftUI updates as the placement of focus within the scene changes.

์”ฌ ๋‚ด ํฌ์ปค์‹ฑ ์œ„์น˜๊ฐ€ ๋ณ€๊ฒฝ๋จ์— ๋”ฐ๋ผ SwiftUI๊ฐ€ ์—…๋ฐ์ดํŠธํ•˜๋Š” ๊ฐ’์„ ์ฝ๊ณ  ์“ธ ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ฃผ๋Š” ํ”„๋กœํผํ‹ฐ ๋ž˜ํผ์ด๋‹ค.

Declaration

@frozen @propertyWrapper
struct FocusState<Value> where Value : Hashable

Overview

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 ํ…์ŠคํŠธ ํ•„๋“œ๊ฐ€ ๋น„์–ด์žˆ๋‹ค๋ฉด ๊ฑฐ๊ธฐ๋กœ ์ด๋™ํ•  ๊ฒƒ์ด๋‹ค.