Reading time: 1 min

This quick recipe shows how to add an underline to any View in SwiftUI. You might want to do that to simulate a certain kind of TextField, or just to add a horizontal divider to a section of your UI.

The end result looks like this:


The recipe is simple: use a VStack to put a Rectangle of small height below your view, ensuring its proximity using the spacing parameter. This View Modifier captures all of it while allowing customizability:

struct UnderlineView: ViewModifier {
  let spacing: CGFloat
  let height: CGFloat
  let color: Color

  func body(content: Content) -> some View {
    VStack(spacing: spacing) {
        .frame(height: height)

Of course, it's a lot easier to use it if it's wrapped in a nice extension method:

extension View {
  func underlined(spacing: CGFloat = 3,
                  height: CGFloat = 0.8,
                  color: Color = .gray) -> some View {
    self.modifier(UnderlineView(spacing: spacing,
                                height: height,
                                color: color))

Then, you can easily use it like this:

TextField("Placeholder", text: $input)

Previous Post