Sticky footer in List SwiftUI - swift

I am trying to implement a sticky footer in a List View in SwiftUI
It doesn't seem to operate the same as the header per say. This is an example of a sticky header implementation
List {
ForEach(0..<10) { index in
Section(header: Text("Hello")) {
ForEach(0..<2) { index2 in
VStack {
Rectangle().frame(height: 600).backgroundColor(Color.blue)
}
}
}.listRowInsets(EdgeInsets())
}
}
This above gives a sticky header situation. Although, once I change Section(header: ... to Section(footer:... it doesn't seem to be sticky anymore, it's simply places at the end of the row.
A more explicit reference
List {
ForEach(0..<10) { index in
Section(footer: Text("Hello")) {
ForEach(0..<2) { index2 in
VStack {
Rectangle().frame(height: 600).backgroundColor(Color.blue)
}
}
}.listRowInsets(EdgeInsets())
}
}
Does anyone have any solutions for this?

With the latest on SwiftUI (2) we now have access to a few more API's
For starters we can use a LazyVStack with a ScrollView to give us pretty good performance, we can then use the pinnedViews API to specify in an array which supplementary view we want to pin or make sticky. We can then use the Section view which wraps our content and specify either a footer or header.
** This code is working as of Xcode beta 2 **
As for using this in a List I'm not too sure, will be interesting to see the performance with List vs Lazy...
struct ContentView: View {
var body: some View {
ScrollView {
LazyVStack(spacing: 10, pinnedViews: [.sectionFooters]) {
ForEach(0..<20, id: \.self) { index in
Section(footer: FooterView(index: index)) {
ForEach(0..<6) { _ in
Rectangle().fill(Color.red).frame(height: 100).id(UUID())
}
}
}
}
}
}
}
struct FooterView: View {
let index: Int
var body: some View {
VStack {
Text("Footer \(index)").padding(5)
}.background(RoundedRectangle(cornerRadius: 4.0).foregroundColor(.green))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

You can use overlay on the List:
struct ContentView: View {
#State private var selectedTab = 0
var body: some View {
TabView(selection: $selectedTab) {
VStack {
List {
ForEach(0..<20, id: \.self) { _ in
Section {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
}
}
.listStyle(InsetGroupedListStyle())
.overlay(
VStack {
Spacer()
Text("Updated at: 5:26 AM")
.font(.footnote)
.foregroundColor(.secondary)
.frame(maxWidth: .infinity)
}
)
}
.tabItem {
Label("First", systemImage: "alarm")
}
Text("Content 2")
.tabItem {
Label("Second", systemImage: "calendar")
}
}
}
}

Related

SwiftUI: Call a function of a programmatically created view

I am trying to make a SwiftUI ScrollView scroll to a certain point in an abstracted view when a button is pressed in a view which is calling the abstracted view programmatically. Here is my code:
struct AbstractedView: View {
#Namespace var view2ID
var body: some View {
ScrollView {
VStack {
View1()
View2()
.id(view2ID)
View3()
}
}
}
func scrollToView2(_ proxy: ScrollViewProxy) {
proxy.scrollTo(view2ID, anchor: .topTrailing)
}
}
As you can see, when scrollToView2() is called (in a ScrollViewReader), the AbstractedView scrolls to view2ID. I am creating a number of AbstractedView's programmatically in a different View:
struct HigherView: View {
var numAbstractedViewsToMake: Int
var body: some View {
VStack {
HStack {
ForEach (0..<numAbstractedViewsToMake, id: \.self) { _ in
AbstractedView()
}
}
Text("button")
.onTapGesture {
/* call each AbstractedView.scrollToView2()
}
}
}
}
If I stored these views in an array in a struct inside my HigherView with a ScrollViewReader for each AbstractedView would that work? I feel as though there has to be a nicer way to achieve this, I just have no clue how to do it. I am new to Swift so thank you for any help.
P.S. I have heard about UIKit but I don't know anything about it, is this the right time to be using that?
Using the comments from #Asperi and #jnpdx, I was able to come up with a more powerful solution than I needed:
class ScrollToModel: ObservableObject {
enum Action {
case end
case top
}
#Published var direction: Action? = nil
}
struct HigherView: View {
#StateObject var vm = ScrollToModel()
var numAbstractedViewsToMake: Int
var body: some View {
VStack {
HStack {
Button(action: { vm.direction = .top }) { // < here
Image(systemName: "arrow.up.to.line")
.padding(.horizontal)
}
Button(action: { vm.direction = .end }) { // << here
Image(systemName: "arrow.down.to.line")
.padding(.horizontal)
}
}
Divider()
HStack {
ForEach(0..<numAbstractedViewsToMake, id: \.self) { _ in
ScrollToModelView(vm: vm)
}
}
}
}
}
struct AbstractedView: View {
#ObservedObject var vm: ScrollToModel
let items = (0..<200).map { $0 } // this is his demo
var body: some View {
VStack {
ScrollViewReader { sp in
ScrollView {
LazyVStack { // this bit can be changed accordingly
ForEach(items, id: \.self) { item in
VStack(alignment: .leading) {
Text("Item \(item)").id(item)
Divider()
}.frame(maxWidth: .infinity).padding(.horizontal)
}
}.onReceive(vm.$direction) { action in
guard !items.isEmpty else { return }
withAnimation {
switch action {
case .top:
sp.scrollTo(items.first!, anchor: .top)
case .end:
sp.scrollTo(items.last!, anchor: .bottom)
default:
return
}
}
}
}
}
}
}
}
Thank you both!

SwiftUI NavigationView Starting Inside Itself

So I've got a NavigationView embedded inside of a TabView that is in the Page View Style. Upon first load the NavigationView will start inside itself, and then once reloaded it shows normally. I am unsure as to what is causing this. And I've made a GIF to better illustrate the problem:
And here is my code:
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
SettingsView()
EmptyView()
EmptyView()
EmptyView()
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
}
struct SettingsView: View {
var body: some View {
NavigationView {
List {
Section(header: Text("General")) {
NavigationLink(destination: SettingsItem(title: "1")) {
Text("1")
}
NavigationLink(destination: SettingsItem(title: "2")) {
Text("2")
}
NavigationLink(destination: SettingsItem(title: "3")) {
Text("3")
}
NavigationLink(destination: SettingsItem(title: "4")) {
Text("4")
}
}
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("Settings")
}
}
}
struct SettingsItem: View {
#State var title = "Title"
var body: some View {
NavigationView {
List {
}
}
.navigationTitle(title)
}
}
struct EmptyView: View {
var body: some View {
ZStack{
Color.green
Text("Empty View")
.padding()
}
.border(Color.black, width: 8)
}
}
Believe it or not, this has nothing to do with the TabView(). This is actually an issue in the SettingsView(). SwiftUI is defaulting to a split view. As a result, you are getting an empty view because you haven't actually navigated to any particular view, with the Settings back button showing. The fix to make this behave as you would expect is to add a .navigationViewStyle(StackNavigationViewStyle() on the NavigationView in SettingsView which forces SettingsView to display as a single view like this:
struct ContentView: View {
var body: some View {
TabView {
SettingsView()
BlankView(color: .green)
BlankView(color: .blue)
BlankView(color: .red)
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
}
struct SettingsView: View {
var body: some View {
NavigationView {
List {
Section(header: Text("General")) {
NavigationLink(destination: SettingsItem(title: "1")) {
Text("1")
}
NavigationLink(destination: SettingsItem(title: "2")) {
Text("2")
}
NavigationLink(destination: SettingsItem(title: "3")) {
Text("3")
}
NavigationLink(destination: SettingsItem(title: "4")) {
Text("4")
}
}
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("Settings")
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct SettingsItem: View {
#State var title = "Title"
var body: some View {
NavigationView {
List {
}
}
.navigationTitle(title)
}
}
struct BlankView: View {
let color: Color
var body: some View {
ZStack{
color
Text("Blank View")
.padding()
}
.border(Color.black, width: 8)
}
}
Also, I edited your code a bit for clarity. EmptyView() is already designated by the system, so I changed it to BlankView() I am not sure why the compiler doesn't have a problem with you naming a struct EmptyView(), but you really shouldn't use that name. I also had the BlankView() show different colors so it was clear you were navigating to separate views.

SwiftUI : Using NavigationView leads to image and text gone

What I'm gonna do is..
If I click a menu, then it goes to a detailed menu-description page.
but It seems to something wrong. the code is the below.
[contentview.swift]
var body: some View {
VStack(alignment:.leading){
List{
Text("Menu")
.font(.title)
.fontWeight(.heavy)
ForEach(menu){ section in
Section(header: Text(section.name) , content: {
ForEach(section.items.indices)
{
index in ItemRow(item:section.items[index])
}
})
}
}.listStyle(GroupedListStyle())
}
}
[ItemRow.swift]
struct ItemRow: View {
let item: MenuItem
var body: some View {
VStack{
//NavigationView{
NavigationLink(destination: ItemDetail(item:item)) {
HStack{
Image(item.thumbnailImage)
VStack(alignment:.leading){
Text(item.name)
.font(.headline)
Text("$\(item.price)")
}
}
}
//}
}
}
}
I intentionally commented out the 'NaviagationView'.
because If I activate that comment relating to NavigationNiew..
See? It seems weird. I still wonder what i did wrong..
Before adding the navigation code, the menu was shown on the Preview well.
Could you give me some tips?
===============================
My Problem has been solved!
[ContentView.swift]
struct ContentView: View {
var body: some View {
ItemList()
}
}
[ItemList.swift]
struct ItemList: View {
var body: some View {
NavigationView{
VStack(alignment:.leading){
List{
Text("Menu")
.font(.title)
.fontWeight(.heavy)
ForEach(menu){ section in
Section(header: Text(section.name) , content: {
ForEach(section.items.indices)
{
index in
//ItemRow(item:section.items[index])
NavigationLink(destination: ItemDetail(item:section.items[index])) {
HStack{
Image(section.items[index].thumbnailImage)
VStack(alignment:.leading){
Text(section.items[index].name)
.font(.headline)
Text("$\(section.items[index].price)")
}
}
}
}
})
}
}.listStyle(GroupedListStyle())
}
}
}
}
There is usually only one NavigationView in an app. It is usually the outer most View.
In this case put it above the VStack in the ContentView.
One of the most common exceptions are sheets.

SwiftUI navigationBarItems disappear in TabView

I have a view that has navigation bar items and I embed that view in a TabView. But when doing that, the bar items no longer appear. If I call the view outside of a TabView everything works as expected.
Below a small sample project to illustrate my issue, note that the TabView is not called on the initial ContentView but later down:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView{
NavigationLink(destination: WarehouseOrderTabView()){
Text("Click me")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct WarehouseOrderTabView: View {
var body: some View {
TabView{
TabView1().navigationBarTitle("Dashboard")
.tabItem {
Image(systemName: "gauge")
Text("Dashboard")
}
TabView2().navigationBarTitle("Orders")
.tabItem {
Image(systemName: "list.dash")
Text("Orders")
}
}
}
}
struct TabView1: View {
var body: some View {
Text("TabView 1")
//I would expect to see those bar items when displaying tab 1
.navigationBarItems(trailing: (
HStack{
Button(action: {
}, label: {
Image(systemName: "arrow.clockwise")
.font(.title)
})
.padding(.init(top: 0, leading: 0, bottom: 0, trailing: 20))
Button(action: {
}, label: {
Image(systemName: "slider.horizontal.3")
.font(.title)
})
}
))
}
}
struct TabView2: View {
var body: some View {
Text("TabView 2")
}
}
What am I missing here?
A NavigationView can be embedded in a TabView and not vice-versa.
TabView contains different tabItem() (at most 5) that can contain your views.
This is how you can use it.
TabView1.swift
struct TabView1: View {
var body: some View {
NavigationView {
Text("TabView 1")
.navigationBarTitle("Dashboard")
.navigationBarItems(trailing:
HStack {
Button(action: {
// more code here
}) {
Image(systemName: "arrow.clockwise")
.font(.title)
}
Button(action: {
// more code here
}) {
Image(systemName: "slider.horizontal.3")
.font(.title)
}
}
)
}
}
}
TabView2.swift
struct TabView2: View {
var body: some View {
NavigationView {
NavigationLink(destination: YourNewView()) {
Text("TabView 1")
}
.navigationBarTitle("Orders")
}
}
}
ContentView.Swift
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
TabView1()
.tabItem {
Image(systemName: "gauge")
Text("Dashboard")
}
TabView2()
.tabItem {
Image(systemName: "list.dash")
Text("Orders")
}
}
}
}
Hope it helps :)

Swiftui navigationLink macOS default/selected state

I build a macOS app in swiftui
i try to create a listview where the first item is preselected. i tried it with the 'selected' state of the navigationLink but it didn't work.
Im pretty much clueless and hope you guys can help me.
The code for creating this list view looks like this.
//personList
struct PersonList: View {
var body: some View {
NavigationView
{
List(personData) { person in
NavigationLink(destination: PersonDetail(person: person))
{
PersonRow(person: person)
}
}.frame(minWidth: 300, maxWidth: 300)
}
}
}
(Other views at the bottom)
This is the normal View when i open the app.
When i click on an item its open like this. Thats the state i want as default opening state when i render this view.
The Code for this view looks like this:
//PersonRow
struct PersonRow: View {
//variables definied
var person: Person
var body: some View {
HStack
{
person.image.resizable().frame(width:50, height:50)
.cornerRadius(25)
.padding(5)
VStack (alignment: .leading)
{
Text(person.firstName + " " + person.lastName)
.fontWeight(.bold)
.padding(5)
Text(person.nickname)
.padding(5)
}
Spacer()
}
}
}
//personDetail
struct PersonDetail: View {
var person : Person
var body: some View {
VStack
{
HStack
{
VStack
{
CircleImage(image: person.image)
Text(person.firstName + " " + person.lastName)
.font(.title)
Text("Turtle Rock")
.font(.subheadline)
}
Spacer()
Text("Subtitle")
.font(.subheadline)
}
Spacer()
}
.padding()
}
}
Thanks in advance!
working example. See how selection is initialized
import SwiftUI
struct Detail: View {
let i: Int
var body: some View {
Text("\(self.i)").font(.system(size: 150)).frame(maxWidth: .infinity)
}
}
struct ContentView: View {
#State var selection: Int?
var body: some View {
HStack(alignment: .top) {
NavigationView {
List {
ForEach(0 ..< 10) { (i) in
NavigationLink(destination: Detail(i: i), tag: i, selection: self.$selection) {
VStack {
Text("Row \(i)")
Divider()
}
}
}.onAppear {
if self.selection != nil {
self.selection = 0
}
}
}.frame(width: 100)
}
}.background(Color.init(NSColor.controlBackgroundColor))
}
}
screenshot
You can define a binding to the selected row and used a List reading this selection. You then initialise the selection to the first person in your person array.
Note that on macOS you do not use NavigationLink, instead you conditionally show the detail view with an if statement inside your NavigationView.
If person is not Identifiable you should add an id: \.self in the loop. This ressembles to:
struct PersonList: View {
#Binding var selectedPerson: Person?
var body: some View {
List(persons, id: \.self, selection: $selectedPerson) { person in // persons is an array of persons
PersonRow(person: person).tag(person)
}
}
}
Then in your main window:
struct ContentView: View {
// First cell will be highlighted and selected
#State private var selectedPerson: Person? = person[0]
var body: some View {
NavigationView {
PersonList(selectedPerson: $selectedPerson)
if selectedPerson != nil {
PersonDetail(person: person!)
}
}
}
}
Your struct person should be Hashable in order to be tagged in the list. If your type is simple enough, adding Hashable conformance should be sufficient:
struct Person: Hashable {
var name: String
// ...
}
There is a nice tutorial using the same principle here if you want a more complete example.
Thanks to this discussion, as a MacOS Beginner, I managed a very basic NavigationView with a list containing two NavigationLinks to choose between two views. I made it very basic to better understand. It might help other beginners.
At start up it will be the first view that will be displayed.
Just modify in ContentView.swift, self.selection = 0 by self.selection = 1 to start with the second view.
FirstView.swift
import SwiftUI
struct FirstView: View {
var body: some View {
Text("(1) Hello, I am the first view")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
SecondView.swift
import SwiftUI
struct SecondView: View {
var body: some View {
Text("(2) Hello, I am the second View")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
#State var selection: Int?
var body: some View {
HStack() {
NavigationView {
List () {
NavigationLink(destination: FirstView(), tag: 0, selection: self.$selection) {
Text("Click Me To Display The First View")
} // End Navigation Link
NavigationLink(destination: SecondView(), tag: 1, selection: self.$selection) {
Text("Click Me To Display The Second View")
} // End Navigation Link
} // End list
.frame(minWidth: 350, maxWidth: 350)
.onAppear {
self.selection = 0
}
} // End NavigationView
.listStyle(SidebarListStyle())
.frame(maxWidth: .infinity, maxHeight: .infinity)
} // End HStack
} // End some View
} // End ContentView
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Result:
import SwiftUI
struct User: Identifiable {
let id: Int
let name: String
}
struct ContentView: View {
#State private var users: [User] = (1...10).map { User(id: $0, name: "user \($0)")}
#State private var selection: User.ID?
var body: some View {
NavigationView {
List(users) { user in
NavigationLink(tag: user.id, selection: $selection) {
Text("\(user.name)'s DetailView")
} label: {
Text(user.name)
}
}
Text("Select one")
}
.onAppear {
if let selection = users.first?.ID {
self.selection = selection
}
}
}
}
You can use make the default selection using onAppear (see above).