Skip to content

Instantly share code, notes, and snippets.

@katsuyoshi
Last active January 9, 2023 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
let invalidColor = Color(red: 1.0, green: 0.7, blue: 0.7)
var body: some View {
VStack {
TextField("Name", text: $name) { editing in
if editing == false {
if isValid {
person.name = name
} else {
isFocused = true
}
}
}
.focused($isFocused)
.background(RoundedRectangle(cornerRadius: 2).fill(isValid ? .clear : invalidColor))
}
.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