Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Created March 28, 2025 01:59
Show Gist options
  • Save Koshimizu-Takehito/dee95507cc11bca81cb634e5b108e538 to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/dee95507cc11bca81cb634e5b108e538 to your computer and use it in GitHub Desktop.
FocusStateのサンプル
import SwiftUI
// MARK: - ContentView
struct ContentView: View {
var body: some View {
MyForm()
.frame(maxHeight: .infinity, alignment: .top)
.padding()
.padding(.top)
}
}
// MARK: - MyForm
struct MyForm: View {
@State var profile = Profile()
@FocusState var focus: KeyPath<Profile, String>?
var body: some View {
VStack(spacing: 20) {
MyTextField("氏名", text: $profile.fullName, isRequired: true)
.focused($focus, equals: \.fullName)
.onSubmit { focus = \.phoneticName }
MyTextField("フリガナ", text: $profile.phoneticName, isRequired: true)
.focused($focus, equals: \.phoneticName)
.onSubmit { focus = \.phoneNumber }
MyTextField("電話番号", text: $profile.phoneNumber)
.focused($focus, equals: \.phoneNumber)
.onSubmit { focus = \.emailAddress }
MyTextField("メールアドレス", text: $profile.emailAddress)
.focused($focus, equals: \.emailAddress)
}
.onAppear {
focus = \.fullName
}
}
}
// MARK: - MyTextField
struct MyTextField: View {
var label: String
var placeholder: String
@Binding var text: String
var isRequired: Bool = false
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 2) {
Text(label)
if isRequired {
Image(systemName: "asterisk")
.imageScale(.small)
.foregroundStyle(.red)
}
}
.font(.subheadline)
.fontWeight(.semibold)
TextField(placeholder, text: $text)
.font(.body)
.textFieldStyle(.roundedBorder)
}
}
}
extension MyTextField {
init(_ label: String, placeholder: String? = nil, text: Binding<String>, isRequired: Bool = false) {
self.init(
label: label, placeholder: placeholder ?? label, text: text, isRequired: isRequired)
}
}
// MARK: - Profile
struct Profile: Hashable, Identifiable {
var id = UUID()
var fullName: String = ""
var phoneticName: String = ""
var phoneNumber: String = ""
var emailAddress: String = ""
}
// MARK: - Preview
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment