Last active
April 19, 2024 12:56
-
-
Save scottmatthewman/722987c9ad40f852e2b6a185f390f88d to your computer and use it in GitHub Desktop.
An example of using Combine to automatically adapt a SwiftUI scrollable view to accommodate an iOS onscreen keyboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Combine | |
struct AdaptsToSoftwareKeyboard: ViewModifier { | |
@State var currentHeight: CGFloat = 0 | |
func body(content: Content) -> some View { | |
content | |
.padding(.bottom, currentHeight) | |
.edgesIgnoringSafeArea(.bottom) | |
.onAppear(perform: subscribeToKeyboardEvents) | |
} | |
private func subscribeToKeyboardEvents() { | |
NotificationCenter.Publisher( | |
center: NotificationCenter.default, | |
name: UIResponder.keyboardWillShowNotification | |
).compactMap { notification in | |
notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect | |
}.map { rect in | |
rect.height | |
}.subscribe(Subscribers.Assign(object: self, keyPath: \.currentHeight)) | |
NotificationCenter.Publisher( | |
center: NotificationCenter.default, | |
name: UIResponder.keyboardWillHideNotification | |
).compactMap { notification in | |
CGFloat.zero | |
}.subscribe(Subscribers.Assign(object: self, keyPath: \.currentHeight)) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct KeyboardAwareScrollableView : View { | |
@ObjectBinding var venue: SomeDataModel | |
var body: some View { | |
// Apply to any view with an instrinsic scroll view – ScrollView, Form, List, etc | |
Form { | |
Section { | |
TextField($venue.name, placeholder: Text("Venue Name")) | |
} | |
Section(header: Text("Address")) { | |
TextField($venue.street, placeholder: Text("Street")) | |
TextField($venue.city, placeholder: Text("City")) | |
TextField($venue.country, placeholder: Text("Country")) | |
TextField($venue.postalCode, placeholder: Text("Postcode/ZIP")) | |
} | |
// etc. | |
} | |
.navigationBarTitle(Text("New venue")) | |
.modifier(AdaptsToSoftwareKeyboard()) // <-- apply the modifier here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will this work for TextEditor?