Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Remove space over navigation title

Is there a way to remove extra space over navigation title (scribbled it in Red in below screenshot). I am working with iOS 15.

enter image description here

Code:

import SwiftUI
import Foundation

struct ContentView: View {
    let names = ["Holly", "Josh", "Rhonda", "Ted"]
    @State private var searchText = ""
    
    /// A site name filter phrase entered by the user.
    @State private var query: String = ""
    
    var body: some View {
        VStack {
            NavigationView {
                VStack {
                    List {
                        ForEach(searchResults, id: \.self) { name in
                            Text(name)
                        }
                    }
                }
                .searchable(
                    text: $query,
                    placement: .navigationBarDrawer(displayMode: .always),
                    prompt: "search"
                )
                .navigationTitle("Explore")
                .background(Color.gray)
            }
            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.gray)
    }
    
    var searchResults: [String] {
        if searchText.isEmpty {
            return names
        } else {
            return names.filter { $0.contains(searchText) }
        }
    }
}
like image 858
tech_human Avatar asked Oct 25 '25 01:10

tech_human


1 Answers

For a large title, that is by design. If you don't want the space, you can use .navigationBarTitleDisplayMode(.inline), but the title would be smaller.

enter image description here

You would need to create your own views if you want a big title, and no space above it.

Though this is a bit hacky, one way I came up with is putting the title in the toolbar:

.toolbar(content: {
    ToolbarItem(placement: .navigationBarLeading) {
        Text("Explore")
            .bold()
            .font(.largeTitle)
    }
})
.padding(.top, -20) // removes the extra top padding added by not having a navigation title

Of course, doing it this way loses the "title turns small when scrolling down" feature.

Result:

enter image description here

like image 88
Sweeper Avatar answered Oct 26 '25 15:10

Sweeper