Skip to content

Instantly share code, notes, and snippets.

@katsuyoshi
Last active January 9, 2023 16:23
Show Gist options
  • Save katsuyoshi/ada0f6f663da52dc093d7c6654a4bb40 to your computer and use it in GitHub Desktop.
Save katsuyoshi/ada0f6f663da52dc093d7c6654a4bb40 to your computer and use it in GitHub Desktop.
TextViewについて
//
// ContentView.swift
// TextFieldPractice
//
// Created by Katsuyoshi Ito on 2023/01/10.
//
import SwiftUI
// CoreDataを想定してOptionalを扱うモデルを用意
struct Person {
var name: String? = nil
}
struct ContentView: View {
@State var person = Person()
@State var name: String = ""
@FocusState var isFocused: Bool
var body: some View {
VStack {
TextField("Name", text: $name) { editing in
if editing == false {
if isValid {
person.name = name
} else {
isFocused = true
}
}
}
.focused($isFocused)
}
.padding()
.onAppear() {
// Optionalの値は一旦nameに展開
name = person.name ?? ""
}
}
private var isValid: Bool {
return !name.isEmpty
}
}
struct ContentView_Previews:
PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment