SwiftUI TabView repeats first entry - swiftui

Xcode RC 14.1
The first tab is generated twice. The first one works, the second brings up a blank screen. This has been reported elsewhere on SO and people suggest removing Spacer()s but this made no difference.
The code below has two variants, one with a enum for the tag as opposed to an integer but they both misbehave identically. (Not sure why all the code hasn't ended up grey below?)
import SwiftUI
struct MenuView: View {
private enum Tab: Hashable {
case location
case calculate
case install
case results
case about
}
// #State private var tabBarSelected: Tab = .location
#State private var selectedTab = 0
var body: some View {
VStack {
TabView(selection: $selectedTab) {
LocationView()
// .tag(Tab.location)
.tag(0)
.tabItem {
Text("Location")
Image(systemName: "globe.europe.africa")
}
CalculateView()
// .tag(Tab.calculate)
.tag(1)
.tabItem {
Text("Calculate")
Image(systemName: "apps.ipad")
}
InstallView()
// .tag(Tab.install)
.tag(2)
.tabItem {
Text("Install")
Image(systemName: "window.ceiling.closed")
}
ResultsView()
.tag(3)
// .tag(Tab.results)
.tabItem {
Text("Results")
Image(systemName: "sun.max.fill")
}
AboutView()
.tag(4)
// .tag(Tab.about)
.tabItem {
Text("About")
Image(systemName: "gear")
}
} // TabView
.accentColor(.yellow) //Active tab color
} // VStack
} // body
init() {
UITabBar.appearance().barTintColor = UIColor.systemGray //TabBar color
UITabBar.appearance().unselectedItemTintColor = UIColor.systemGray2
UITabBar.appearance().isOpaque = false
}
}
struct MenuView_Previews: PreviewProvider {
static var previews: some View {
MenuView()
}
}

You need to wrap your content in a VStack, kindly check your code in LocationView().
Instead of this:
var body: some View {
Text("Hi")
Text("welcome")
}
Use the code below:
var body: some View {
VStack {
Text("Hi")
Text("welcome")
}
}

Related

SwiftUI .searchable implementation in the wrong way?

I am trying to use a tab bar in order to use different views. On some of those views I have a list of items and I wish that list to be .searchable. If I go to each of the views and search it works like a charm, but when I embed that in the tabbed view the list becomes non-responsive to click but it responds to scroll gesture.
I will expand the idea with code that I have and screenshots, but I am pretty sure that the problem resides in how I'm implementing the combination of the tab bar view and the views that have the searchable modifier:
This code works well
import SwiftUI
struct ClientListView: View {
#ObservedObject var viewModel = ClientFeedViewModel()
#State var searchText: String
#State private var showingSheet = false
#State private var showList = false
var clients: [Client] {
if searchText.count > 2 {
return searchText.isEmpty ? viewModel.clients : viewModel.search(withText: searchText)
}
return viewModel.clients
}
init(){
searchText = ""
}
var body: some View {
NavigationView {
List(clients) { client in
NavigationLink(destination: {
}, label: {
VStack {
Text(client.clientName)
}
})
.listRowSeparator(.hidden)
}
.searchable(text: $searchText)
.listStyle(.plain)
}
}
}
struct ClientListView_Previews: PreviewProvider {
static var previews: some View {
ClientListView()
}
}
The problem starts when I do this and implement the ClientListView in a tab bar view like this:
Tab bar with different views not working searchable modifier
This is the code of the Tab Bar View:
import SwiftUI
struct MainTabView: View {
#EnvironmentObject var viewModel: AuthViewModel
#Binding var selectedIndex: Int
var body: some View {
NavigationView {
VStack {
TabView(selection: $selectedIndex) {
ClientListView()
.onTapGesture {
selectedIndex = 0
}
.tabItem {
Label("Clients", systemImage: "list.bullet")
}.tag(0)
ProjectListView()
.onTapGesture {
selectedIndex = 1
}
.tabItem {
Image(systemName: "person")
Label("Projects", systemImage: "list.dash")
}.tag(1)
TaskListView()
.tabItem {
Image(systemName: "person")
Label("Tasks", systemImage: "list.dash")
}.tag(2)
.onTapGesture {
selectedIndex = 2
}
ClientListView()
.tabItem {
Label("Settings", systemImage: "gear")
}.tag(3)
.onTapGesture {
selectedIndex = 3
}
}
.navigationTitle(tabTitle)
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Image("logo_silueta")
.resizable()
.scaledToFit()
.frame(width: 30, height: 30)
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
viewModel.signOut()
}, label: {
Text("logout")
})
}
}
.navigationBarTitleDisplayMode(.inline)
}
}
var tabTitle: String {
switch selectedIndex {
case 0: return "Clients"
case 1: return "Projects"
case 2: return "Tasks"
case 3: return "Settings"
default: return ""
}
}
}
struct MainTabView_Previews: PreviewProvider {
static var previews: some View {
MainTabView(selectedIndex: .constant(0))
}
}
Navigation on the tabbed view works and displays the different names on the tab bar title, but when I click cancel or x button of the search bar, it doesn't work and also the list becomes unclickable
So far I haven't been able to find where the problem is but I am assuming its because the tab bar view is messing up with the searchable property
The culprit would seem to be your .onTapGesture modifiers, which will take precedence over any tap handling in your child views.
I'm not sure what value those modifiers bring, since using appropriate .tag values is enough for the tab view to keep track of its selected index. I'd start by removing them.
#ObservedObject var viewModel = ClientFeedViewModel() is a memory leak, try changing it to something like:
struct ClientListViewData {
var searchText: String = ""
var showingSheet = false
var showList = false
mutating func showSheet() {
showingSheet = true
}
}
struct ClientListView: View {
#Binding var data: ClientListViewData

Broken NavigationView Layout SwiftUI on TabView and TabViewStyle set to .page

I have the following code
enum Tab {
case accounts, lootbox
}
struct ContentView: View {
#State private var currentTab:Tab = .lootbox
var body: some View {
TabView(selection: $currentTab){
AccountView()
.tabItem {
Label("Accounts", systemImage: "person.crop.circle")
}
.tag(Tab.accounts)
Lootbox()
.tabItem {
Label("Lootbox", systemImage: "shippingbox")
}
.tag(Tab.lootbox)
}
.tabViewStyle(.page)
}
}
struct AccountView: View {
var body: some View {
NavigationView{
VStack{
Text("AccountView")
Spacer()
.navigationTitle("Lootbox")
}
}
.navigationViewStyle(.stack)
}
}
struct Lootbox: View {
var body: some View {
NavigationView{
VStack{
Text("Lootbox")
Spacer()
}
.navigationTitle("Lootbox")
}
.navigationViewStyle(.stack)
}
}
The VStackhides behind the navigation view title. After swiping right and left, it is as expected. Why is that? Or is this a bug of SwiftUI?
Before swipe left and right:
After (how it should be):

SwiftUI problem with not reloading Tab Item when using NavigationLink

I'm using Navigation View inside TabView and the problem is that if I an on Tab A and with NavigationView I open other Views, when changing from tab A to B and after a while I came back to tab A I dosen't reload tab A from beginning but it show the last View open with NavitagionLink. The problem is that in each View I'm getting data from a DB and because of that if shows an empty view.
My ContentView looks like this:
struct ContentView: View {
#ObservedObject var appState = AppState()
#State var currentTab : Tab
var body: some View {
TabView(selection: $appState.currentTab) {
NavigationView {
HomeView(appState: appState)
}
.tabItem {
if appState.currentTab == .home {
Image(systemName: "house.fill")
} else {
Image(systemName: "house")
}
Text(LocalizedStringKey("HomeTabMenu"))
}.tag(Tab.home)
NavigationView {
SearchView()
}
.tabItem {
if appState.currentTab == .search {
Image(systemName: "magnifyingglass.circle.fill")
} else {
Image(systemName: "magnifyingglass")
}
Text(LocalizedStringKey("SearchTabMenu"))
}.tag(Tab.search)
NavigationView {
AddItemView(appState: appState)
}
.tabItem {
if appState.currentTab == .add {
Image(systemName: "plus.circle.fill")
} else {
Image(systemName: "plus.circle")
}
Text(LocalizedStringKey("SellTabMenu"))
}.tag(Tab.add)
NavigationView {
ShoppingCartFavoritesView()
}
.tabItem {
if appState.currentTab == .favorites {
Image(systemName: "cart.fill")
} else {
Image(systemName: "cart")
}
Text(LocalizedStringKey("CartTabMenu"))
}.tag(Tab.favorites)
NavigationView {
ProfileView(appState: appState)
}
.tabItem {
if appState.currentTab == .profile {
Image(systemName: "person.fill")
} else {
Image(systemName: "person")
}
Text(LocalizedStringKey("ProfileTabMenu"))
}.tag(Tab.profile)
}//End TabView
.accentColor(Color("ColorMainDark"))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(currentTab: Tab.home)
}
}
class AppState: ObservableObject {
#Published var currentTab : Tab = .home
}
enum Tab {
case home, search, add, favorites, profile
}
And if I open SearchView()
struct SearchView: View {
var body: some View {
NavigationLink(destination: View_2(id: "ABC")){
Text("ABC")
}
}
}
struct View_2: View {
#ObservedObject var performSearchProducts = PerformSearchInProducts()
var id : String
var body: some View {
ScollView {
ForEach(performSearchProducts.products) { product in
Text(product.name)
}
}.onAppear(perform: {
self.performSearchProducts.searchSubCategory(id: id)
})
}
}
If in SearchView I'm on View_2() and the I open another Tab, when I come back to tab SearchView it doesn't show the SearchView(), but it remains on View_2() with the back button in navigation bar.
How can I make to show SearchView() and not keep the state of NavigationLink?
It's the default behavior. Attach id to TabView.
}//End TabView
.accentColor(Color("ColorMainDark"))
.id(appState.currentTab) //<--Here

SwiftUI NavigationView Not Fully Extending In View

I am working with NavigationView in SwiftUI and having an issue with it extending fully to the bottom of the screen.
I created a simple List in and this works fine. However, when I put it in a NavigationView, it creates a gray area at the bottom. I've tried adjusting the frame and a number of other things to no avail. I've never seen this before. Any help would be appreciated.
struct ListingView: View {
var body: some View {
List(0..<5) { item in
Text("Test")
}
}
}
struct ListingView: View {
var body: some View {
NavigationView {
List(0..<5) { item in
Text("Test")
}
}
}
}
struct ContentView: View {
// PacificBlue Background Set Up.
init() {
UITabBar.appearance().isTranslucent = false
UITabBar.appearance().barTintColor = UIColor(Color.pacificBlue)
}
// MARK: View
var body: some View {
TabView {
SeafoodListView()
.tabItem {
Image(systemName: "line.diagonal.arrow")
Text("Market")
}.tag(0) // SeafoodMarketView
ListingView()
.tabItem {
Image(systemName: "list.bullet.rectangle")
Text("Listings")
}.tag(1) // ListingView
RequestView()
.tabItem {
Image(systemName: "megaphone")
Text("Requests")
}.tag(2) // RequestView
MessengerView()
.tabItem {
Image(systemName: "ellipsis.bubble")
Text("Messenger")
}.tag(3) // MessengerView
AccountView()
.tabItem {
Image(systemName: "person")
Text("Account")
}.tag(4) // AccountView
} // TabView
.accentColor(.white)
}
}
// MARK: Preview
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This is due to hack with appearance...
init() {
// UITabBar.appearance().isTranslucent = false // remove this line !!!
UITabBar.appearance().barTintColor = UIColor(Color.pacificBlue)
}
Alternate: replace entire appearance with configured opaque background
init() {
let newAppearance = UITabBarAppearance()
newAppearance.configureWithOpaqueBackground()
newAppearance.backgroundColor = UIColor(Color.pacificBlue)
UITabBar.appearance().standardAppearance = newAppearance
}

SwiftUI, setting title to child views of TabView inside of NavigationView does not work

Why I am putting TabView into a NavigationView is because I need to hide the bottom tab bar when user goes into 2nd level 'detail' views which have their own bottom action bar.
But doing this leads to another issue: all the 1st level 'list' views hosted by TabView no longer display their titles. Below is a sample code:
import SwiftUI
enum Gender: String {
case female, male
}
let members: [Gender: [String]] = [
Gender.female: ["Emma", "Olivia", "Ava"], Gender.male: ["Liam", "Noah", "William"]
]
struct TabItem: View {
let image: String
let label: String
var body: some View {
VStack {
Image(systemName: image).imageScale(.large)
Text(label)
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
TabView {
ListView(gender: .female).tag(0).tabItem {
TabItem(image: "person.crop.circle", label: Gender.female.rawValue)
}
ListView(gender: .male).tag(1).tabItem {
TabItem(image: "person.crop.circle.fill", label: Gender.male.rawValue)
}
}
}
}
}
struct ListView: View {
let gender: Gender
var body: some View {
let names = members[gender]!
return List {
ForEach(0..<names.count, id: \.self) { index in
NavigationLink(destination: DetailView(name: names[index])) {
Text(names[index])
}
}
}.navigationBarTitle(Text(gender.rawValue), displayMode: .inline)
}
}
struct DetailView: View {
let name: String
var body: some View {
ZStack {
VStack {
Text("profile views")
}
VStack {
Spacer()
HStack {
Spacer()
TabItem(image: "pencil.circle", label: "Edit")
Spacer()
TabItem(image: "minus.circle", label: "Delete")
Spacer()
}
}
}
.navigationBarTitle(Text(name), displayMode: .inline)
}
}
What I could do is to have a #State var title in the root view and pass the binding to all the list views, then have those list views to set their title back to root view on appear. But I just don't feel so right about it, is there any better way of doing this? Thanks for any help.
The idea is to join TabView selection with NavigationView content dynamically.
Demo:
Here is simplified code depicting approach (with using your views). The NavigationView and TabView just position independently in ZStack, but content of NavigationView depends on the selection of TabView (which content is just stub), thus they don't bother each other. Also in such case it becomes possible to hide/unhide TabView depending on some condition - in this case, for simplicity, presence of root list view.
struct TestTabsOverNavigation: View {
#State private var tabVisible = true
#State private var selectedTab: Int = 0
var body: some View {
ZStack(alignment: .bottom) {
contentView
tabBar
}
}
var contentView: some View {
NavigationView {
ListView(gender: selectedTab == 0 ? .female : .male)
.onAppear {
withAnimation {
self.tabVisible = true
}
}
.onDisappear {
withAnimation {
self.tabVisible = false
}
}
}
}
var tabBar: some View {
TabView(selection: $selectedTab) {
Rectangle().fill(Color.clear).tag(0).tabItem {
TabItem(image: "person.crop.circle", label: Gender.female.rawValue)
}
Rectangle().fill(Color.clear).tag(1).tabItem {
TabItem(image: "person.crop.circle.fill", label: Gender.male.rawValue)
}
}
.frame(height: 50) // << !! might be platform dependent
.opacity(tabVisible ? 1.0 : 0.0)
}
}
This maybe a late answer, but the TabView items need to be assigned tag number else binding selection parameter won't happen. Here is how I do the same thing on my project:
#State private var selectedTab:Int = 0
private var pageTitles = ["Home", "Customers","Sales", "More"]
var body: some View {
NavigationView{
TabView(selection: $selectedTab, content:{
HomeView()
.tabItem {
Image(systemName: "house.fill")
Text(pageTitles[0])
}.tag(0)
CustomerListView()
.tabItem {
Image(systemName: "rectangle.stack.person.crop.fill")
Text(pageTitles[1])
}.tag(1)
SaleView()
.tabItem {
Image(systemName: "tag.fill")
Text(pageTitles[2])
}.tag(2)
MoreView()
.tabItem {
Image(systemName: "ellipsis.circle.fill")
Text(pageTitles[3])
}.tag(3)
})
.navigationBarTitle(Text(pageTitles[selectedTab]),displayMode:.inline)
.font(.headline)
}
}