You can do the something natively in swiftUI without using UIKit. See here:https://developer.apple.com/documentation/swiftui/textfield/focused(_:equals:)
struct LoginForm {
enum Field: Hashable {
case usernameField
case passwordField
}
@State private var username = ""
@State private var password = ""
@FocusState private var focusedField: Field?
var body: some View {
Form {
TextField("Username", text: $username)
.focused($focusedField, equals: .usernameField)
SecureField("Password", text: $password)
.focused($focusedField, equals: .passwordField)
EmptyView()
.emptyState(focusedField == .username) {
Text("Please enter a user name.")
.foregroundColor(.red)
.font(.footnote)
}
Button("Sign In") {
if username.isEmpty {
focusedField = .usernameField
} else if password.isEmpty {
focusedField = .passwordField
} else {
handleLogin(username, password)
}
}
}
}
}
struct EmptyStateViewModifier<EmptyContent>: ViewModifier where EmptyContent: View {
var isEmpty: Bool
let emptyContent: () -> EmptyContent
func body(content: Content) -> some View {
if isEmpty {
emptyContent()
} else {
content
}
}
}
extension View {
func emptyState<EmptyContent>(_ isEmpty: Bool,
emptyContent: @escaping () -> EmptyContent) -> some View where EmptyContent: View {
modifier(EmptyStateViewModifier(isEmpty: isEmpty, emptyContent: emptyContent))
}
}