I have a SwiftUI app that is targeting iOS 14 as well.
I want to use the focus state only for the iOS 15 version. I don’t mind much about the iOS 14 version. As focusState is only available for iOS 15.
@FocusState private var isUsernameFocused: Bool = false
I tried to define with #available but it is not working.
Again, I just want to use it with iOS 15 machines, but I need a way to declare it.
I want to use it on a press of a button.
Whenever I press the button, I want to active the keyboard for the text field.
How can I do this on SwiftUI?
2
Answers
You didn’t say how you want to use it, but generally the approach can be like this:
View
, which will be compatible with iOS 15 only and will contain@FocusState
, as well as encapsulate any behaviors specific to the focus (they can be predefined or passed in oninit
):if #available(iOS 15, *
to show thisFocusableUsername
, or just a regular `TextField (or whatever the component you are using):Of course you may need to control the behavior of this field from outside, so you can pass a main view as a delegate to it for example, or pass some closures to run – many options there.
This is what I came up with:
From your main view you’d call autoFocusTextField with the required arguments (obviously, you can tweak them).