List in swiftui

Notes on list in SwiftUI

You get a lot of interface for very little code. Making tables is a joy without the masses of boilerplate code needed to set up data sources and delegates. The instant preview in the canvas makes iteration much easier. Being able to create something like a Picker and having SwiftUI render it in one of multiple different styles depending on the platform is magical.


  • A sort of “IndexedForEach” that works similarly to how a ViewModifier works, but for multiple items
  • Ref:
  • And with index:
struct EnumeratedForEach<ItemType, ContentView: View>: View { 
    let data: [ItemType]
    let content: (Int, ItemType) -> ContentView
    init(_ data: [ItemType], @ViewBuilder content: @escaping (Int, ItemType) -> ContentView) { = data
        self.content = content
    var body: some View {
        ForEach(Array(zip(data.indices, data)), id: \.0) { idx, item in
            content(idx, item)
// Now you can use it like this:
EnumeratedForEach(items) { idx, item in

Creating table:

If you come from UIKit, you will appreciate how easy it is to create tables in SwiftUI. Gone are the days of cell prototypes, data sources, and delegates.

Now, all you need to do is create a List view, pass it an array with your data and declare which views to use as rows.

struct FilmListView: View {
    var body: some View {
        List(TestData.films, id: \.title) { film in
            FilmRow(film: film)

struct FilmListView_Previews: PreviewProvider {
    static var previews: some View {

struct FilmRow: View {
    let film: Film
    var body: some View {
        HStack(spacing: 24.0) {
                .frame(width: 70.0, height: 110.0)
                .shadow(color: .gray, radius: 10.0, x: 4.0, y: 4.0)
            VStack(alignment: .leading, spacing: 4.0) {
                Group {

struct FilmRow_Previews: PreviewProvider {
    static var previews: some View {
        FilmRow(film: TestData.films[0])

Adding delete and move:

struct FilmsView: View {
    @State var films: [Film] = TestData.films
    var body: some View {
        List {
            ForEach (films, id: \.title) { film in
                FilmRow(film: film)
            .onMove { (source, destination) in
                self.films.move(fromOffsets: source, toOffset: destination)
            .onDelete { offsets in
                self.films.remove(atOffsets: offsets)

First of all, any mutable data in a SwiftUI app needs to be stored in @State and @ObservedObject properties. You can get my free guide on architecting SwiftUI apps with MVC and MVVM to know when to use each.

In SwiftUI, we affect the appearance of views by changing the parameters of initializers and view modifiers.

Whenever a view in SwiftUI needs to update data that resides somewhere else, we use a binding. A binding is a reference that reaches data stored elsewhere, which, in SwiftUI, is called the single source of truth.

@Binding var film: Film // we pass movie in the init

Button(action: { }) {
    LikeIcon(isFilled: film.isLiked)


static let film = TestData.films[0]
DetailsView(film: .constant(film))
            Group {
                SideDetails(film: .constant(film))
                BottomDetails(film: film)
// Notice that a $ sign precedes the film parameter for the SideDetails view. This is a SwiftUI operator you use to connect bindings to data.
SideDetails(film: $film)

You can connect bindings to @State and @ObservedObject properties, or other bindings, like in this case. These chains of bindings allow us to pass changes up the view hierarchy until we reach the single source of truth. To know more

While the main navigation of an iOS app is managed by architectural views like NavigationView and TabView, modal presentation happens through three view modifiers:

the .alert modifier shows a small alert panel in the middle of the screen, with one or two buttons; the .actionSheet modifier presents a menu with several options; the .sheet modifier presents a full-screen view.


        "FilmName":"Alita: Battle Angel",
        "Duration":"122 min",
        "Category":"Action, Adventure, Sci-Fi, Thriller",
        "Filmmaker":"Robert Rodriguez",
        "Performers":"Rosa Salazar, Christoph Waltz, Jennifer Connelly, Mahershala Ali",
        "Storyline":"A deactivated cyborg is revived, but cannot remember anything of her past life and goes on a quest to find out who she is.",
        "Accolades":"8 wins & 25 nominations.",
struct Film: Decodable {
    let name: String
    let releaseYear: String
    let duration: String
    let category: String
    let filmmaker: String
    let performers: String
    let storyline: String
    let origin: String
    let accolades: String
    let coverImage: String
struct TestData {
	static var movies: [Movie] = {
		let url = Bundle.main.url(forResource: "Movies", withExtension: "json")!
		let data = try! Data(contentsOf: url)
		let decoder = JSONDecoder()
		return try! decoder.decode([Movie].self, from: data)

preview cells:

struct DecisionCell_Previews: PreviewProvider {
   static var previews: some View {
           decision: Decision(handValue: 6, dealerCardValue: .nine, action: .hit), myHandValue: 8, dealerCardValue: .five)

_PreviewOrientation returns a Group containing the original View in portrait and landscape modes:

struct _PreviewOrientation<Value: View>: View {
   private let viewToPreview: Value

   init(_ viewToPreview: Value) {
       self.viewToPreview = viewToPreview

   var body: some View {
       Group {

To use this view builder in a preview, simply pass in the View you’re previewing:

struct ContentView_Previews: PreviewProvider {
   static var previews: some View {

Selectable list

  • selectable list: (List doesn’t support rendering and scrolling in a horizontal axis)

  • SwiftUI’s built in List selection functionality doesn’t allow for much customization. Here is a way to do it manually:

  1. Create a state that is an optional int
  2. Create a list where id is the int. List(Array(items.indecies), id: \.self)
  3. Create items: { i in let item = items[i] }
  4. Set the state on tap of the list item
  5. Change the selection state by doing: let isSelected = selectedIndex == i
  6. Change selected state in the item: let row = Row(isSelected: isSelected)

Native picker button:

There is also detail view as picker: and 4 other picker styles here:

struct ContentView: View {
    @State private var selectedItem: Int = 0
    var body: some View {
        VStack {
            // 1
            Picker("Color", selection: $selectedItem) {
        .toolbar {
            ToolbarItem {
                // 2
                Picker("Color", selection: $selectedItem) {

Creating a picker button manually:

Menu {
    ForEach(options, id: \.self) { text in
        Button(text) { Swift.print("action!"); action() }  // Label("Add", systemImage: "")
} label: {
    HStack {
        Image(optionalSystemName: leadingImageName)? // left
            .iconStyle(size: 18, padding: 0)
        Text(self.options[0]) // right
        Image(systemName: imageName)
            .iconStyle(size: 16, padding: 0)


A list that is meant as input:

Form resources:

  • Lots of different form setups (a bit old swift ui, some doesnt work out the box etc, and some work)
  • Really nice for settings form:
  • Dropdown groups + customization:
  • formstyle:


  • If all else fails, there is always accessing uikit from swiftui
  • List styles:
  • adjusting list row seperator insets (horizontal):
  • remove row seperator:
  • Hide row seperator:
  • Content inset for scrollview and list:
  • Content inset on the scrollview:
  • Cell with link:
  • remove first row seperator:
  • hidelast seperator:
  • Scrollable list:
  • Simple list from array of items adhering to identifiable protocol:

Other resources:

  • dynamic list:
  • foreach vs list:
  • scrollview:
  • nuanced info on scrolling:
  • scroll to start and end:
  • scroll position detection:
  • using scrollviewreader: and and and and
  • advance scrolling in swiftui via uikit:
  • tracking current scroll item:
  • Nuanced scrollview info:
  • observing content offset: and
  • has custom snapping for hstack:
  • Get the current position of ScrollView in SwiftUI
  • pull to refresh:
  • pagination:
  • styling:
  • oldschool UIKit wheel picker: