Remove space created on List items in view - SwiftUI [duplicate] - swiftui

I'm having an issues with a List inside a NavigationView since iOS 14 update.
Here is a simple breakdown of the code - I've striped everything that doesn't show the issue
struct ContentView: View {
var views = ["Line 1", "Line 2", "Line 3"]
var body: some View {
NavigationView {
VStack {
List {
ForEach(views, id: \.self) { view in
VStack {
Text("\(view)")
}
.background(Color.red)
}
}
}
}
}
}
This produces the following result:
I cant work out why the list is hovering in the center of the navigation view like that. As far as I can tell this should produce a listview that takes up all avaliable space (with the exception of the top where navigationbar would be).
Indeed when run on iOS 13.5 that is the result I get as pictured below:
I've had a read through the documentation but cant work out why this behaviour is suddenly happening.
Any help would be greatly appreciated.
Thanks

Problem
It looks like the default styles of a List or NavigationView in iOS 14 may in some cases be different than in iOS 13.
Solution #1 - explicit listStyle
It's no longer always the PlainListStyle (as in iOS 13) but sometimes the InsetGroupedListStyle as well.
You need to explicitly specify the listStyle to PlainListStyle:
.listStyle(PlainListStyle())
Example:
struct ContentView: View {
var views = ["Line 1", "Line 2", "Line 3"]
var body: some View {
NavigationView {
VStack {
List {
ForEach(views, id: \.self) { view in
VStack {
Text("\(view)")
}
.background(Color.red)
}
}
.listStyle(PlainListStyle()) // <- add here
}
}
}
}
Solution #2 - explicit navigationViewStyle
It looks like the NavigationView's default style can sometimes be the DoubleColumnNavigationViewStyle (even on iPhones).
You can try setting the navigationViewStyle to the StackNavigationViewStyle (as in iOS 13):
.navigationViewStyle(StackNavigationViewStyle())
Example:
struct ContentView: View {
var views = ["Line 1", "Line 2", "Line 3"]
var body: some View {
NavigationView {
VStack {
List {
ForEach(views, id: \.self) { view in
VStack {
Text("\(view)")
}
.background(Color.red)
}
}
}
}
.navigationViewStyle(StackNavigationViewStyle()) // <- add here
}
}

Related

SwiftUI extra space at top of list above section header. On testing device only

I have been trying to figure out what is causing the space at the top of the screen in my production app, so I made this test app to see if it is a bug or not. The code works as intended on a simulator but when a testing device runs the code it adds extra space. The space goes away after you start scrolling, and does not comeback until the view reloads. I have tried restarting the device and other devices. I took out .navigationTitle and .navigationBarTitleDisplayMode and it did not fix the problem. So far my best guess is that there is some problem with changing the section header in .onAppear(). Changing it to .task() seems to be a workaround for now.
struct DetailView: View {
#State var item: Item
#State private var headerText = "Header"
var body: some View {
List {
Section(header: Text("\(headerText)")) {
Text("Text")
}
HStack {
Text("Red Text")
}.listRowBackground(Color.red)
// Change to .task instead
}.onAppear {
headerText = "Change Header"
}
}
}
Edit: Here is the code for the list view, it is the default new project setup.
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink(destination: DetailView(item: item), label: {
Text(item.timestamp!, formatter: itemFormatter)
})
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
Text("Select an item")
}
}
In my case this behaviour was caused by .navigationViewStyle(StackNavigationViewStyle()).
Looks like it's a bug with NavigationView in SwiftUI 4 since it wasn't like this before.
If you are on iOS 16 use NavigationStack instead NavigationView. This fixed all my problems and I didn't even need to use the navigationViewStyle anymore.
NavigationView is deprecated in favor of NavigationStack.

Navigation + Tabview + Sheet broken in iOS 15

It looks like Navigation + TabView + Sheet is broken in iOS 15.
When I do this:
ContentView -> DetailView -> Bottom Sheet
When the bottom sheet comes up, the Detail view is automatically popped off the stack:
https://www.youtube.com/watch?v=gguLptAx0l4
I expect the Detail view to stay there even when the bottom sheet appears. Does anyone have any idea on why this happens and how to fix it?
Here is my sample code:
import Combine
import SwiftUI
import RealmSwift
struct ContentView: View {
var body: some View {
NavigationView {
TabView {
TabItemView(num: 1)
.tabItem {
Text("One")
}
TabItemView(num: 2)
.tabItem {
Text("Two")
}
}
}
}
}
struct TabItemView: View {
private let num: Int
init(num: Int) {
self.num = num
}
var body: some View {
NavigationLink(destination: DetailView(text: "Detail View \(num)")) {
Text("Go to Detail View")
}
}
}
struct DetailView: View {
#State private var showingSheet = false
private let text: String
init(text: String) {
self.text = text
}
var body: some View {
Button("Open Sheet") {
showingSheet.toggle()
}.sheet(isPresented: $showingSheet) {
Text("Sheet Text")
}
}
}
This works on iOS 14 btw
UPDATE 1:
Tried #Sebastian's suggestion of putting NavigationView inside of TabView. While this fixed the nav bug, it fundamentally changed the behavior (I don't want to show the tabs in DetailView).
Also tried his suggestion of using Introspect to set navigationController.hidesBottomBarWhenPushed = true on the NavigationLink destination, but that didn't do anything:
struct ContentView: View {
var body: some View {
TabView {
NavigationView {
TabItemView(num: 1)
}.tabItem {
Text("One")
}
NavigationView {
TabItemView(num: 2)
}.tabItem {
Text("Two")
}
}
}
}
struct TabItemView: View {
private let num: Int
init(num: Int) {
self.num = num
}
var body: some View {
NavigationLink(destination: DetailView(text: "Detail View \(num)").introspectNavigationController { navigationController in
navigationController.hidesBottomBarWhenPushed = true
}) {
Text("Go to Detail View")
}
}
}
struct DetailView: View {
#State private var showingSheet = false
private let text: String
init(text: String) {
self.text = text
}
var body: some View {
Button("Open Sheet") {
showingSheet.toggle()
}.sheet(isPresented: $showingSheet) {
Text("Sheet Text")
}
}
}
You need to flip how you nest TabView & NavigationView. Instead of nesting several TabView views inside a NavigationView, use the TabView as the parent component, with a NavigationView for each tab.
This is how the updated ContentView would look like:
struct ContentView: View {
var body: some View {
TabView {
NavigationView {
TabItemView(num: 1)
}
.tabItem {
Text("One")
}
NavigationView {
TabItemView(num: 2)
}
.tabItem {
Text("Two")
}
}
}
}
This makes sense and is more correct: The tabs should always be visible, but you want to show a different navigation stack with different content in each tab.
That it worked previously doesn't make it more correct - SwiftUI probably just changed its mind on dealing with unexpected situations. That, and the lack of error messages in these situations, is the downside of using a framework that tries to render anything you throw at it!
If the goal is specifically to hide the tabs when pushing a new view on a NavigationView (e.g., when tapping on a conversation in a messaging app), you have to use a different solution. Apple added the UIViewController.hidesBottomBarWhenPushed property to UIKit to support this specific use case.
This property is set on the UIViewController that, when presented, should not show a toolbar. In other words: Not the UINavigationController or the UITabBarController, but the child UIViewController that you push onto the UINavigationController.
This property is not supported in SwiftUI natively. You could set it using SwiftUI-Introspect, or simply write the navigation structure of your application using UIKit and write the views inside in SwiftUI, linking them using UIHostingViewController.

Make List Sections non-collapsible in SwiftUI when embedded into a NavigationView SwiftUI

When I embed a List grouped into Sections into a NavigationView the section headers become collapsible. I'd like to keep them non-collapsible, just like when the List is not embedded into the NavigationView.
My current code (with the NavigationView):
import SwiftUI
struct MyGroup {
var name:String, items:[String]
}
struct ContentView: View {
var groups : [MyGroup] = [
.init(name: "Animals", items: ["🐕","🐩","🐂","🐄","🐈","🦩","🐿","🐇"]),
.init(name: "Vehicles", items: ["🚕","🚗","🚃","🚂","🚟","🚤","🛥","⛵️"])]
var body: some View {
NavigationView {
VStack {
List {
ForEach(groups, id: \.self.name) { group in
Section(header: Text(group.name)) {
ForEach(group.items, id:\.self) { item in
Text(item)
}
}
}
}
}.navigationTitle("collections")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
It is default style applied, you can make it explicitly set for List like below (tested with Xcode 12 / iOS 14)
List {
ForEach(groups, id: \.self.name) { group in
Section(header: Text(group.name)) {
ForEach(group.items, id:\.self) { item in
Text(item)
}
}
}
}.listStyle(InsetGroupedListStyle()) // or GroupedListStyle
Just using the SidebarListStyle in listStyle modifier
.listStyle(SidebarListStyle())
In case you're stumbling on this... The issue doesn't have anything to do with being embedded in a NavigationView as the OP and #Danial mentioned. It's because it's embedded in the the VStack at the first level of the NavigationView in the example code. Seems like a SwiftUI bug to me.

navigationBarItems moves list to the right [duplicate]

I'm having an issues with a List inside a NavigationView since iOS 14 update.
Here is a simple breakdown of the code - I've striped everything that doesn't show the issue
struct ContentView: View {
var views = ["Line 1", "Line 2", "Line 3"]
var body: some View {
NavigationView {
VStack {
List {
ForEach(views, id: \.self) { view in
VStack {
Text("\(view)")
}
.background(Color.red)
}
}
}
}
}
}
This produces the following result:
I cant work out why the list is hovering in the center of the navigation view like that. As far as I can tell this should produce a listview that takes up all avaliable space (with the exception of the top where navigationbar would be).
Indeed when run on iOS 13.5 that is the result I get as pictured below:
I've had a read through the documentation but cant work out why this behaviour is suddenly happening.
Any help would be greatly appreciated.
Thanks
Problem
It looks like the default styles of a List or NavigationView in iOS 14 may in some cases be different than in iOS 13.
Solution #1 - explicit listStyle
It's no longer always the PlainListStyle (as in iOS 13) but sometimes the InsetGroupedListStyle as well.
You need to explicitly specify the listStyle to PlainListStyle:
.listStyle(PlainListStyle())
Example:
struct ContentView: View {
var views = ["Line 1", "Line 2", "Line 3"]
var body: some View {
NavigationView {
VStack {
List {
ForEach(views, id: \.self) { view in
VStack {
Text("\(view)")
}
.background(Color.red)
}
}
.listStyle(PlainListStyle()) // <- add here
}
}
}
}
Solution #2 - explicit navigationViewStyle
It looks like the NavigationView's default style can sometimes be the DoubleColumnNavigationViewStyle (even on iPhones).
You can try setting the navigationViewStyle to the StackNavigationViewStyle (as in iOS 13):
.navigationViewStyle(StackNavigationViewStyle())
Example:
struct ContentView: View {
var views = ["Line 1", "Line 2", "Line 3"]
var body: some View {
NavigationView {
VStack {
List {
ForEach(views, id: \.self) { view in
VStack {
Text("\(view)")
}
.background(Color.red)
}
}
}
}
.navigationViewStyle(StackNavigationViewStyle()) // <- add here
}
}

Corrupted Navigation Views

I'm pretty sure this is a bug in SwiftUI, but I wondered if anyone has encountered it and figured out a workaround. My normal use case is to have a search field appear, but I've simplified it to the point where a simple text string exhibits the bug.
Create a single-view app, copy this into ContentView, and run it. Tap the search icon twice, then scroll the view; you'll see the text scrolling UNDER the title.
import SwiftUI
struct ContentView: View {
private var items = (0 ... 50).map {String($0)}
#State private var condition = false
var searchButton: some View {
Button(action: {self.condition.toggle()}) {
Image(systemName: "magnifyingglass").imageScale(.large)
}
}
var body: some View {
NavigationView {
VStack {
if condition {
Text("Peekaboo")
}
List {
ForEach(items, id: \.self) {item in
HStack {
Text(item)
}
}
}
}
.navigationBarTitle("List of Items")
.navigationBarItems(leading: searchButton)
}
}
}
Maybe it is a bug, submit feedback to Apple, but currently this is how NavigationView behaves - it collapses navigation bar only if its top content is List/ScrollView/Form. So to solve the issue move your VStack either into a List or out of NavigationView
1)
var body: some View {
NavigationView {
List {
if condition {
Text("Peekaboo")
}
ForEach(items, id: \.self) {item in
2)
var body: some View {
VStack {
if condition {
Text("Peekaboo")
}
NavigationView {
List {
It seems that a View cannot cope with variable number of views.
A workaround this strange behavior is this:
import SwiftUI
struct ContentView: View {
private var items = (0 ... 50).map {String($0)}
#State private var condition = false
var searchButton: some View {
Button(action: {self.condition.toggle()}) {
Image(systemName: "magnifyingglass").imageScale(.large)
}
}
var body: some View {
NavigationView {
VStack {
if condition {
Text("Peekaboo")
} else {
Text("")
}
// or use this Text(condition ? "Peekaboo" : "")
List {
ForEach(items, id: \.self) {item in
HStack {
Text(item)
}
}
}
}
.navigationBarTitle("List of Items")
.navigationBarItems(leading: searchButton)
}
}
}
Let me know if it works, if not let us know what device/system you are using. Tested with Xcode 11.6 beta, Mac 10.15.5, target ios 13.5 and mac catalyst.