Last active
April 1, 2025 16:41
-
-
Save JamesSedlacek/2d0425319e2a854da8c51f4b05c9842a to your computer and use it in GitHub Desktop.
SwiftUI Keyboard Toolbar Workaround
This file contains hidden or 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
// | |
// KeyboardToolbar.swift | |
// | |
// Created by James Sedlacek on 9/20/23. | |
// | |
import SwiftUI | |
import Combine | |
@Observable | |
final class KeyboardToolbarViewModel { | |
var isKeyboardVisible = false | |
private var cancellables = Set<AnyCancellable>() | |
init() { | |
NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification) | |
.sink { [weak self] _ in | |
withAnimation(.easeIn.delay(0.15)) { | |
self?.isKeyboardVisible = true | |
} | |
} | |
.store(in: &cancellables) | |
NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification) | |
.sink { [weak self] _ in | |
self?.isKeyboardVisible = false | |
} | |
.store(in: &cancellables) | |
} | |
} | |
struct KeyboardToolbar<V: View>: ViewModifier { | |
@State private var viewModel: KeyboardToolbarViewModel = .init() | |
private let toolbar: V | |
init(@ViewBuilder toolbar: () -> V) { | |
self.toolbar = toolbar() | |
} | |
func body(content: Content) -> some View { | |
content | |
.safeAreaInset(edge: .bottom) { | |
if viewModel.isKeyboardVisible { | |
toolbar | |
} | |
} | |
} | |
} | |
extension View { | |
func keyboardToolbar<V: View>(view: @escaping () -> V) -> some View { | |
modifier(KeyboardToolbar(toolbar: view)) | |
} | |
func keyboardDoneButton() -> some View { | |
modifier(KeyboardToolbar { | |
HStack { | |
Spacer() | |
Button("Done") { | |
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) | |
} | |
.padding(.horizontal) | |
} | |
.frame(height: 49) | |
.background(.bar) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@JamesSedlacek Hi, thx for sharing the workaround for the toolbar issues, could you make an example to show how to add done button with this snippet? Thank you. 🙇♂️