Swift Dev Notes
SedatOnat.devAffiliated with SedatOnat.com
  • 👋Welcome to SedatOnat.dev
  • Learning Path
    • What to Learn?
    • How to Learn?
    • Useful Docs
      • Articles
      • Best Practices
      • Event Notes
        • Kodluyoruz
          • GIT - What is Markdown? How to use it?
        • NS Istanbul
          • Trendyol Super App
        • NS Spain
          • SoundCloud SwiftUI Experiences
        • Patika Events
          • Rust at a Glance
          • Being an IOS Developer
          • Mobil Uygulamamdan Nasıl Gelir Elde Ederim?
          • Tecrübeniz Yoksa Yazılımcı Portfolyosu Var: Peki Nasıl Olacak?
          • Yazılımda trend olan başlıklar nelerdir? Hype teknolojilere kapılmalı mıyım?
          • GitHub Profilinizin Önemi ve Geliştirmeniz İçin Öneriler
          • Patika LaunchPad
          • Özgür Kaya - Yazılım Test/Otomasyon Uzmanı Olmak
          • Türkay Ürkmez
          • Patika Derslerini Bitirsek Yazılımcı Olabilir Miyiz?
          • Performanslı ve Kaliteli Kod Yazmak
          • Yazılım Kariyeri İsteyenler: Nereden Başlamak Gerek?
          • Yazılımcılar dikkat burnout var
          • Yazılım Sektöründe Kariyer Tavsiyeleri
          • Front-End Kariyerine başlangıç
          • Öğrenmeniz gereken iş fırsatları: MNM Teknoloji ile PHP Symphony & Magento
          • Yurtdışı kariyer imkanı
          • Mezunlarımıza soralım: Bootcamp hızlandırmadan işe girmeye giden yolculuk
          • Savunma sektörünce mühendis olmak
          • Everything you need to know about technical interviews at top global companies
          • Java ve Framework 'leri - Akın Kaldıroğlu
          • React Native 'e dair Merak Edilenler
          • FAQs about being an Assistant at Patika
          • Career Journey - From Medical Faculty to Software Development
          • How to make your own game?
          • Altogic ile Backend uygulama geliştirmeyi baştan sonra anlayalım
          • Backend Developer Olmaya karar verdim, peki ya sonra?
          • Bir bilene soralım - .Net Framework 'e İlişkin merak ettikleriniz
          • Bir bilene soralım - Go Developer Olmak
          • Bir bilene soralım - Angular hakkında merak edilenler
          • Bu yaz kodlama konusunda kendime nasıl yatırımlar yapabilirim?
        • Tea-Coffee-Human
          • Where to Start for Coding?
        • Ugur Umutoglu
          • Nasıl Mobile Developer Oldum?
        • Yusuf Demirci
          • Nasıl iOS Developer Olarak İlk İşimi Buldum
          • Amsterdam 'da yazılımcı olmak
          • Nasıl iOS Developer Olurum
      • Insights
      • Job Application Notes
      • Media to use in Apps (Authorized)
      • Q&A
      • Quotes
      • Terminology
  • Before Starting
    • Xcode
      • Folder Attributes
      • Project Transfer
      • Shortcuts
      • Annotation
    • Version Control
      • Xcode Cloud
      • GIT
      • GitHub
      • GitLab
      • BitBucket
      • GitKraken
      • SourceTree
    • Swift
      • Declarative vs Imperative Languages
      • Things to Remember
    • Naming
  • DATABASES
    • Apple Database
      • CloudKit
      • CoreData
        • NSError
        • NSFetchRequest
        • NSManagedObject
        • NSMergePolicy
        • NSPredicate
        • FetchRequest
        • Relationships
        • .hasChanges
      • KeyChain
      • UserDefaults
    • 3rd Party Databases
      • AWS Amplify
      • Firebase
      • JSON
      • MySQL
      • ORM
      • Realm
      • SQL Lite
    • Database Comparison
  • Design Patterns
    • Alternatives
      • Clean Swift
      • MVC
      • MVI
      • MVVM
      • Uber RIB
      • Viper
    • Comparison
  • Model
    • Accessibility
    • Assets
    • Error Debugging
    • File Management
  • CODES
    • Pseudo Code
    • Frameworks
      • Cocoa
      • CodeScanner
      • CoreHaptics
      • CoreImage
      • Foundation
      • LocalAuthentication
      • MapKit
      • ?SwiftDate
      • Swinject
      • SwiftUI
      • UIKit
      • UserNotifications
    • APIs
      • AlamoFire
      • Apple URL Loading System
      • ChatGPT
      • Create ML
      • Wikipedia: Map Coordinates
    • Packages
    • Dependency Managers
      • Carthage
      • CocoaPods
      • SPM - Swift Package Manager
    • Libraries
      • RxSwift
      • KingFischer
      • ?SwiftLint
      • Moya
    • Main Pillars (Protocol, Class, Struct, etc.)
      • Protocols
        • OOP vs POP
        • Codable
        • Comparable
        • Equatable
        • Hashable
        • Identifiable
        • Observable
        • ObservableObject
        • PreviewProvider
        • Shape
        • View
      • Protocol vs Class
      • Classes
        • Adding Initializer to a ChildClass
        • Copying Classes
        • Deinitializer
        • Final Class
        • Override
        • Restart the Inheritance
        • Working with Variables
      • Class vs Struct
      • Structs
      • Functions
      • Closures
        • Closure: Escaping
    • Data Collectors
      • Arrays
        • Stride
      • Dictionaries
      • Enums (Enumerations)
      • Sets
      • Tuples
    • Properties / Data Containers
      • Constants
      • Variables
    • Property Wrappers
      • AppStorage
      • Binding
      • Dynamic Language Lookup
      • Environment
      • EnvironmentObject
      • FocusState
      • MainActor
      • Observed
      • Observed vs. State
      • ObservedObject
      • Published
      • State
      • State vs. StateObject
      • StateObject
    • Optionals
    • Data Types
      • Booleans
      • Date-Time
      • Numbers
      • Strings
      • Type Annotations
    • Operators
    • Conditionals
      • on...
      • Triggers
    • Loops
    • Physical Properties
      • Camera
      • Dynamic Island
      • Gestures
      • Haptics
      • Notifications
      • Sensors
        • Bluetooth
        • Camera
        • FaceID
        • GPS
        • Gyroscope
        • LIDAR
        • Microphone
        • NFC
        • TouchID / FingerPrint
        • WiFi
      • Speakers
    • Other Properties
      • Siri
      • Widgets
    • Code Pool
      • Text Modifiers
        • Adding and/or
        • .autocapitalization(.none)
        • .joined
        • Text Cases
        • TextEditor
        • Text Styles
      • Others
        • AssertionFailure
        • async/await
        • .constant
        • defer
        • .dismiss
        • extensions
        • Filtering
        • ForEach
        • .formatted()
        • init
        • isMultiple(of:)
        • map()
        • .random
        • .randomElement
        • .removeDublicates()
        • Result
        • self
        • .shuffled
        • .sink
        • SortDescriptor
        • Static let
        • Stepper
        • Super.
        • TabView()
        • Timer
  • View
    • Apple HIG
    • Design
      • Pool
      • Tools
    • Image and Graphic
      • CG - Core Graphics
        • CGAffineTransform
        • CGFloat
        • CGPoint
        • CGRect
        • CGSize
        • Path
      • CI - Core Image
        • CIContext
        • CIFilter
        • CIImage
      • Image
        • Image Modifiers...
          • .background
        • GeometryReader
      • NSObject
      • QR Code
    • Page Elements
      • Button
        • PushButton
      • CheckList
      • Confirmation Dialog
      • Context Menu
      • Display Modes
      • Divider
      • Drag and Drop List
      • Form
      • Grid
      • Group
      • GroupBox
      • Keyboard
      • Label
      • LazyView
      • List
        • .listStyle
      • NavigationLink
      • NavigationSplitView
      • NavigationStack
      • NavigationView
      • NavigationView vs NavigationStack
      • OutlineGroup
      • Picker
      • ProgressView()
      • ScrollView
      • Section
      • Shapes
        • Arc
        • Circle
        • Rectangle
      • sheet()
      • Slider
      • Stacks
      • TextField
      • Toggle
      • Toolbar
      • ViewBuilder
      • WindowGroup
    • View Modifiers
      • .alert
      • .alignment
      • .alignmenGuide
      • .animation
      • .blendMode
      • .blur()
      • .clipShape
      • Color
      • .contentShape
      • .disabled
      • .drawingGroup
      • .fill
      • .ignoreSafeArea
      • .inset
      • .isPresented
      • .navigationBarTitleDisplayMode
      • .navigationTitle
      • .overlay
      • .offset
      • .opacity
      • .padding
      • .position
      • .preferredColorScheme
      • .rotation
      • .scaleEffect
      • .searchable
      • stroke and strokeBorder
      • .task
      • .toggle
      • .trailingIcon
      • .transition
    • Reporting
    • Others
      • AsyncImage
      • Switching Views
      • Drawing
  • Solutions
    • Case Solutions
      • Solutions Pool
        • Adding to Favorites
      • Solutions for: Views
        • Solutions for: Button
        • Solutions for: Dark Mode Color Examples
        • Solutions for: Frame Modifier
        • Solutions for: Gooey Effect
        • Solutions for: List
        • Solutions for: Login Screen
        • Solutions for: Other Elements
        • Solutions for: Star Rating
        • Solutions for: Scrolling
        • Solutions for: Theme
    • Sample Project Pool
  • Testing
    • Debugging
      • Debug View Hierarchy (Xcode)
      • Profile your SwiftUI code and identify slow layouts
    • Testing CheckList
    • Unit Test
  • Documentation
    • GitBook
      • GitBook Page Template
      • GitBook Shortcuts
      • GitBook Documentation
    • MarkDown
  • Deploying and Publishing
    • Checklist
    • Deployment Processes
    • Publishing Processes
      • Reasons of Rejection
    • ASO - App Store Optimization
  • Kaizen
    • CI-CD
Powered by GitBook
On this page
  • Overview
  • Subjects
  • Form vs List
  • Edge to Edge Color
  • List with row number
  • List with Sections
  • Sorted List
  • Swipe Actions
  • Adding options with Swipe Actions
  • Sorting the List
  • Sources
  • Videos
  • Articles / Documents

Was this helpful?

  1. View
  2. Page Elements

List

#list

Overview

Subjects

Form vs List

  • Form is for User Input

  • List is for Presentation of data

Edge to Edge Color

Edge to edge color
.listStyle(.plain)

List with row number

Let list =["Car", "Bike", "Plane", "Boat"]

for(index, element) inlist.enumerated() {
    
print(index, ":", element)
}

// 
print: 
0 : Car
1 : Bike
2 : Plane
3 : Boat

List with Sections

VStack {
    List {
        ForEach(countries, id: \.self) { country in
            Section(country.wrappedFullName) {
                ForEach(country.candyArray, id: \.self) { candy in
                    Text(candy.wrappedName)
                }
            }
        }
    }

Sorted List

// FIRST METHOD
struct User: Identifiable {
    let id = UUID()
    let firstName: String
    let lastName: String
}

struct ContentView: View {
let users = [
    User(firstName: "Arnold", lastName: "Rimmer"),
    User(firstName: "Kristine", lastName: "Kochanski"),
    User(firstName: "David", lastName: "Lister"),
].sorted {
    $0.lastName < $1.lastName
}

//.............................

// SECOND METHOD

struct User: Identifiable {
    let id = UUID()
    let firstName: String
    let lastName: String
    
    static func <(lhs: User, rhs: User) -> Bool {
        lhs.lastName < rhs.lastName
    }
    
}

struct ContentView: View {
let users = [
    User(firstName: "Arnold", lastName: "Rimmer"),
    User(firstName: "Kristine", lastName: "Kochanski"),
    User(firstName: "David", lastName: "Lister"),
].sorted()
}

The result is the same on both methods. The benefit is, in case of using this list everywhere with same sorting method, we can change the sorting method in the struct and it changes everywhere we use the list.

Swipe Actions

Double Sided Swipe Action
List {
    Text("Taylor Swift")
        .swipeActions {
            Button(role: .destructive) {
                print("Hi")
            } label: {
                Label("Delete", systemImage: "minus.circle")
            }
        }
        .swipeActions(edge: .leading) {
            Button {
                print("Hi")
            } label: {
                Label("Pin", systemImage: "pin")
            }
            .tint(.orange)
        }
}

Other sources

Adding options with Swipe Actions

Sorting the List

Define the alternatives

enum SortOption {
    case alt1, alt1Reversed, alt2, alt2Reversed
    }

Convert enum type to variable and Publish it

@Published var sortOption: SortOption = .alt2

Sources

Videos

Articles / Documents

PreviousLazyViewNext.listStyle

Last updated 2 years ago

Was this helpful?

Peter Friese / The Ultimate Guide to SwiftUI List Views - Part 4 / Swipe Actions in SwiftUI 3
Peter Friese / The Ultimate Guide to SwiftUI List Views - Part 2 / Building Dynamic Lists in SwiftUI
Peter Friese / The Ultimate Guide to SwiftUI List Views - Part 2 / Building Static Lists in SwiftUI
Peter Friese / The Ultimate Guide to SwiftUI List Views - Part 3 / Styling List Views
https://stackoverflow.com/questions/24028421/how-to-iterate-a-loop-with-index-and-element-in-swift/24028458#24028458
Hacking with Swift / 100 Days / Day-68 - Adding conformance to Comparable for custom types
Result
Hacking with Swift / 100 Days / Day-81 - Adding custom row swipe actions to a List
Hacking with Swift / 100 Days / Day-83 - Adding options with swipe actions