Pinning a View to the Bottom of the Safe Area in SwiftUI

KD Knowledge Diet
2 min readMay 25, 2024

In SwiftUI, pinning a view to the bottom of the screen within the safe area is a common requirement for various app interfaces. Whether you’re designing a chat app or simply need a view to remain fixed at the bottom of the screen, SwiftUI makes it straightforward to achieve this. In this guide, we’ll explore how to permanently position a view at the bottom of the safe area, even when the software keyboard appears.

Using safeAreaInset:

To pin a view to the bottom of the safe area, we can utilize the `safeAreaInset` modifier in SwiftUI. This modifier allows us to place a view within the safe area and automatically adjusts its position when the safe area changes, such as when the software keyboard appears.

Here’s an example of how to create a chat-like interface with a text field pinned to the bottom of the safe area:

List(messages) { message in
Text(message.text)
}
.safeAreaInset(edge: .bottom) {
TextField(
"New message",
text: $newMessageText
)
.padding()
.textFieldStyle(.roundedBorder)
.background(.ultraThinMaterial)
.onSubmit {
// Handle user submission, e.g., append a new message
}
}

In this code snippet:

1. We have a `List` that displays messages, which can be any kind of data you’re presenting in your app.

2. The `safeAreaInset` modifier is applied to the `TextField`, and we specify `.bottom` to indicate that we want to pin it to the bottom of the safe area. This ensures that the text field remains visible even when the software keyboard appears.

3. The `TextField` is customized with padding, a rounded border, and a background style. You can adjust these styling options to match your app’s design.

4. The `onSubmit` closure is used to handle user submissions. For example, you can append a new message to the list of messages when the user presses the return key.

Achieving a Polished UI:

To enhance the user experience, you can add a material background to the `TextField`. This background style allows the scrolled content to appear beneath the text field, creating a smoother visual transition.

By following this approach, you can easily create a user-friendly chat interface or any other layout where you need to pin a view to the bottom of the safe area in SwiftUI.

Conclusion:

In SwiftUI, pinning a view to the bottom of the safe area is a straightforward task, thanks to the `safeAreaInset` modifier. Whether you’re building a chat app or any interface that requires a fixed bottom view, you can achieve it with just a few lines of code. This ensures that your app’s layout remains responsive, even when the software keyboard is presented to the user. Happy SwiftUI coding! 🚀

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!