I'm trying to put two Text views above a SearchBar in a NavigationView. Is there a way to minimize the space between the SearchBar and the Text views above it? See screenshot.
Also, is my code optimal this way or can I implement all elements in one?
Find below a sample of what I've currently done.
import SwiftUI
struct HomeView: View {
@State private var searchText = ""
var body: some View {
VStack(alignment: .leading) {
Text("Hi There!")
.font(.largeTitle)
.fontWeight(.heavy)
.multilineTextAlignment(.leading)
.foregroundColor(Color(red: 0.388, green: 0.231, blue: 1.0))
.padding([.top, .leading])
Text("Are you ready to work out?")
.fontWeight(.heavy)
.bold()
.foregroundColor(.gray)
.padding(.leading)
NavigationView {
Text("")
.navigationTitle("Your Plans")
.searchable(text: $searchText)
}
}
}
}
struct SettingsView: View {
var body: some View {
Text("Your Profile")
.font(.largeTitle)
.fontWeight(.heavy)
.multilineTextAlignment(.leading)
.foregroundColor(Color(red: 0.388, green: 0.231, blue: 1.0))
.position(x: 125, y: 70)
}
}
struct ContentView: View {
var body: some View {
TabView{
HomeView()
.tabItem {
Text("Training")
.foregroundColor(Color(red:0.388, green: 0.231, blue: 1.0))
}
SettingsView()
.tabItem () {
Image(systemName: "slider.vertical.3")
}
.foregroundColor(Color(red: 0.388, green: 0.231, blue: 1.0))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(.dark)
}
}
Instead of using a NavigationView, you can do the following:
struct ContentView: View {
@State private var searchText = ""
var body: some View {
VStack(alignment: .leading, spacing: 40) {
VStack(alignment: .leading) {
Text("Hi There!")
.font(.largeTitle)
.fontWeight(.heavy)
.multilineTextAlignment(.leading)
.foregroundColor(Color(red: 0.388, green: 0.231, blue: 1.0))
Text("Are you ready to work out?")
.fontWeight(.heavy)
.bold()
.foregroundColor(.gray)
}
VStack(alignment: .leading, spacing: 3) {
Text("Your Plans")
.font(.largeTitle)
.fontWeight(.heavy)
SearchBar(text: $searchText)
}
Spacer()
}
.padding()
}
}
struct SearchBar: View {
@Binding var text: String
@State private var isEditing = true
var body: some View {
HStack(spacing: 4) {
Image(systemName: "magnifyingglass")
.foregroundColor(.secondary)
TextField("Search", text: $text)
.onTapGesture {
self.isEditing = true
}
}
.frame(height: 45)
.padding(.horizontal, 8)
.background(Color(.systemGray6))
.cornerRadius(15)
}
}
PS: I have deliberately made the SearchBar view simple for brevity. You should add more functionality to it in a production application.