DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


How to create a List View in Swift UI without using MVVM ? 2022

  • 5 minutes read
  • 190 Views
How to create a List View in Swift UI without using MVVM ? 2022

    Table of Contents

How to start a new iOS project in Xcode?

To create a new ios project, Open Xcode on your Mac and click on ‘Create a New Xcde Project’

create-a-new-xcode-project-swift-ui.png

In the next window, select ‘ios’ from the top menu and then select ‘App’ and click on Next

create-new-ios-app-swift-ui.png

In the next screen, choose the name of your app e.g. “ListSample” and leave everything else as it is i.e. Interface - SwiftUI, Language - Swift, and Use Core Data, Include Tests untick, save it at your desired location and start the project.

Note - This app will have SwiftUI Life Cycle and you won’t get the old StoryBoard options of UIKit, if you still wish to have it choose StoryBoard in the Interface

create-a-new-xcode-project-swift-ui-2.png

In the next window, you will get the playground to code into, To the very left you will get the list of all the files to work on. For this tutorial, we will be using ‘ContentView.swift’ file, clicking on it would open it on the editor to the right and you can open a canvas of your favorite device to see the live preview of the code.

create-a-list-inswift-ui.png

First of all we will declare a Item struct, it would have two properties, id and name at the very top outside the ContentView struct. Our code would look like this:-

import SwiftUI

struct Item : Identifiable { 
    var id : UUID
    var name : String
}

struct ContentView: View {

Basically, we need to have just the name of the item, but we have used id and given it default kind UUID so that we can make this struct identifiable and use it in For each function of list.

Now, we will create an array of Items in the ContentView

 var items = [Item(id:UUID(), name:"First Item"),Item(id:UUID(), name:"Second Item") ]

Now in the body, we will show the list :-

         List{
            ForEach(items){item in
                Text(item.name)
            }
        }

The complete code till now looks like this:-

import SwiftUI

struct Item : Identifiable {
    var id : UUID
    var name : String
}

struct ContentView: View {

    var items = [Item(id:UUID(), name:"First Item"),Item(id:UUID(), name:"Second Item") ]

    var body: some View {
        List{
            ForEach(items){item in
                Text(item.name)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

And the preview looks like this:-

create-list-swift-ui-mvvm.png

How to add functionality of deleting an item in List View of Swift UI?

Now, we will add a delete functionality to delete the item using the swipe option and change our code of list to as under:-

List{
            ForEach(items){item in
                Text(item.name)
            }
            .onDelete(perform : {IndexSet in for
                 index in IndexSet {
                items.remove(at: index)
            }
            })
        }

Also, we will make our items a State Property so that it can identify a change in the app and get modified accordingly.

@State var items = [Item(id:UUID(), name:"First Item"),Item(id:UUID(), name:"Second Item") ]

How to add an option to move the items of list in SwiftUI?

Now, we will add an option to move the objects and for that we will and onMove() to the list

.onMove(perform: {
                indices, newOffset in
                items.move(fromOffsets: indices, toOffset: newOffset)
            })

But for this to work, we need to be in edit mode and for that we need an edit button, the quickest way of having an edit button is by having it at the very top. So we will add a NavigationView to our List View and add the navigationBarTitle

  NavigationView{

            List{
                ForEach(items){item in
                    Text(item.name)
                }
                .onDelete(perform : {IndexSet in for
                     index in IndexSet {
                    items.remove(at: index)
                }
                })
                .onMove(perform: {
                    indices, newOffset in
                    items.move(fromOffsets: indices, toOffset: newOffset)
                })
            }
            .navigationBarTitle(Text("To Do"), displayMode: .large)

        }

One more thing to note here is that the .navigationBarTitle() modifier is not applied to the NavigationView but to it’s child.

How to add edit button in list in SwiftUI?

Now to add the edit button :-

.navigationBarTitle(Text("To Do"), displayMode: .large)
            .toolbar(content: {
                EditButton()
            })

Now, in your live preview, you can see that you can have got the edit button, where you can click and then move the items up and down.

Now, we can also add an optoin to create a new item for the modify your code to as under:-

 .navigationBarTitle(Text("To Do"), displayMode: .large)
            .toolbar(content: {
                ToolbarItemGroup(placement: .navigationBarTrailing){
                    EditButton()
                    Button(action: {
                        items.append(Item(id:UUID(), name:"New Item"))
                    }, label: {Image(systemName: "plus")})

                }

            })

We can further link it to the next page by just using the NavigationLink

 List{
                ForEach(items){item in
                    NavigationLink(destination: {
                        Text("Destination \(item.name)")
                    }, label: {Text(item.name)})
                }

Now, we have got small navigation icons at the end of each row and we can navigate to the next page, which for now will only show the Desitination and name of the item.

Sample code to create a List View in Swift UI

The complete code upto this point is as under:-

import SwiftUI

struct Item : Identifiable {
    var id : UUID
    var name : String
}

struct ContentView: View {

    @State var items = [Item(id:UUID(), name:"First Item"),Item(id:UUID(), name:"Second Item") ]

    var body: some View {
        NavigationView{

            List{
                ForEach(items){item in
                    NavigationLink(destination: {
                        Text("Destination \(item.name)")
                    }, label: {Text(item.name)})
                }
                .onDelete(perform : {IndexSet in for
                    index in IndexSet {
                    items.remove(at: index)
                }
                })
                .onMove(perform: {
                    indices, newOffset in
                    items.move(fromOffsets: indices, toOffset: newOffset)
                })
            }
            .navigationBarTitle(Text("To Do"), displayMode: .large)
            .toolbar(content: {
                ToolbarItemGroup(placement: .navigationBarTrailing){
                    EditButton()
                    Button(action: {
                        items.append(Item(id:UUID(), name:"New Item"))
                    }, label: {Image(systemName: "plus")})
                }
            })
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

So, our code is ready and working, but the only issue with it the code has become very long and if we have to add more functionality, it will further make the code more hefty and unmanageable. So to solve this issue, we tend to use MVVM which stand for Model View View Model Pattern and in our next tutorial, we will turn our code to use the benefits of MVVM thus making it more usable.


Related Posts

How to show a Popup alert on First Launch of an app in Swift UI?
By Udit Vashisht

How to create a pop-up alert/ display alert in SwiftUI?

In this tutorial, we will learn to show/create a pop up alert on the first launch of Swift UI. I hope that you all know how to start a new project in Swift UI, if not, you can refer to ...

Read More
How to show an alert in SwiftUI?
By Udit Vashisht

How to show an alert in SwiftUI?

When we use SwiftUI, we can show alerts to the user with the alert() modifier. How that works depends on whether we want to target iOS 15 and later or iOS 13 and 14. I’ll show you both ways, but the newer iOS ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python