仕事用ブログに書くほどではない技術ネタ
Copilotの答え。iOS17でwarning発生
import SwiftUI import Combine struct ContentView: View { @State private var email: String = "" @State private var isValidEmail: Bool = true var body: some View { VStack { TextField("Enter your email", text: $email) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() .onChange(of: email, perform: { value in isValidEmail = validateEmail(value) }) if !isValidEmail { Text("Invalid email address") .foregroundColor(.red) .padding() } } .padding() } func validateEmail(_ email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
おしい。手直し。
iOS17対応版
import SwiftUI struct ContentView: View { @State private var email: String = "" @State private var isValidEmail: Bool = true var body: some View { VStack { TextField("Enter your email", text: $email) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() .onChange(of: email) { validateEmail(email) } .onSubmit { validateEmail(email) } if !isValidEmail { Text("Invalid email address") .foregroundColor(.red) .padding() } } .padding() } func validateEmail(_ email: String) { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) isValidEmail = emailPred.evaluate(with: email) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
まだ新しいコードに弱いみたい。
Warning
修正後の動作確認
iOS18は大変そう。