Last active
January 9, 2023 16:23
-
-
Save katsuyoshi/ada0f6f663da52dc093d7c6654a4bb40 to your computer and use it in GitHub Desktop.
TextViewについて
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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