@@ -2,25 +2,20 @@ import SwiftUI
22
33/// Autofocus for `TextField` and `TextEditor` in iOS 15 and later
44///
5+ @available ( iOS 15 . 0 , * )
56struct AutofocusTextModifier : ViewModifier {
67
7- @available ( iOS 15 . 0 , * )
88 @FocusState private var textFieldIsFocused : Bool
99
1010 func body( content: Content ) -> some View {
11- if #available( iOS 15 . 0 , * ) {
12- content
13- . focused ( $textFieldIsFocused)
14- . onAppear {
15- // Without delay '.focused' will not work. This might fix in later releases.
16- DispatchQueue . main. asyncAfter ( deadline: . now( ) + 0.6 ) {
17- textFieldIsFocused = true
18- }
11+ content
12+ . focused ( $textFieldIsFocused)
13+ . onAppear {
14+ // Without delay '.focused' will not work. This might fix in later releases.
15+ DispatchQueue . main. asyncAfter ( deadline: . now( ) + 0.6 ) {
16+ textFieldIsFocused = true
1917 }
20- }
21- else {
22- content
23- }
18+ }
2419 }
2520}
2621
@@ -32,6 +27,14 @@ extension View {
3227 /// Autofocus in `TextField` and `TextEditor` is available only for iOS15+
3328 ///
3429 func focused( ) -> some View {
35- self . modifier ( AutofocusTextModifier ( ) )
30+ // Conditional check has to be done inside the Group function builder,
31+ // otherwise the iOS 15 modifier will be loaded into memory and the app will crash.
32+ Group {
33+ if #available( iOS 15 . 0 , * ) {
34+ self . modifier ( AutofocusTextModifier ( ) )
35+ } else {
36+ self
37+ }
38+ }
3639 }
3740}
0 commit comments