Automatic Dynamic Keyboard Pop-Up in SwiftUI ⌨️

Muhammad Naufal Adli
2 min readFeb 20, 2024

--

( source: by naufal adli )

SwiftUI offers a clean and intuitive way to create user interfaces across Apple platforms. One common requirement in many apps is the need for a keyboard to pop up automatically when a specific action is triggered. In this article, we’ll explore how to achieve automatic keyboard pop-up in SwiftUI, accompanied by a detailed explanation of the provided code.

Achieving Automatic Keyboard Pop-Up

( source: by naufal adli )

The key to achieving automatic keyboard pop-up lies in SwiftUI’s focused modifier and the @FocusState property wrapper. In the TextSheet view, the focused($showkeyboard) modifier is applied to the TextEditor, ensuring that the keyboard automatically appears when the sheet is presented. First create Button(“ start typing ”) ContentView:

//
// ContentView.swift
// DynamicKeyboard
//
// Created by Naufal Adli on 20/02/24.
//

import SwiftUI

struct ContentView: View {
@State var showView = false
var body: some View {
VStack{
Button(action: { showView.toggle() }, label: {
Label("Start typing", systemImage: "Keyboard.fill")
})
.tint(.green)
.buttonStyle(.bordered)
.controlSize(.large)
}.padding()
.sheet(isPresented: $showView){
TextSheet()
}
}
}

And than create TextSheet view:

( source: by naufal adli )

Before we dissect the code, let’s focus on the TextSheet struct, which encapsulates the sheet content:

//
// TextSheet.swift
// DynamicKeyboard
//
// Created by Naufal Adli on 20/02/24.
//

import SwiftUI

struct TextSheet: View {
@State var text = ""
@FocusState var showkeyboard : Bool
var body: some View {
NavigationStack{
Text("Type something below:")
.font(.headline)
.foregroundColor(.secondary)
.multilineTextAlignment(.leading)
.frame(maxWidth: .infinity,alignment: .leading)
.padding(.leading,20)

TextEditor(text: $text)
.bold().font(.title)
.padding(12)
.focused($showkeyboard)
.navigationTitle("Dynamic keyboard")
}.onAppear{
showkeyboard = true
}
}
}

Resources

If you’d like to take a look at the project’s full code, you can find it here:
https://github.com/naufaladli0406/Automatic-Keyboard-Pop-Up

Thanks for reading! Stay tuned for more SwiftUI articles by Muhammad Naufal Adli which will be coming soon and dont forget to clap. this artikel make Hand-crafted & Made with❤️.

--

--

Muhammad Naufal Adli
Muhammad Naufal Adli

Written by Muhammad Naufal Adli

Informatic Engineer Student 🧑‍💻|| Enjoy learning new things and sharing with everyone🙌

Responses (1)