30 Days of SwiftUI - Day 16: Lists, Words, and Launchpads: Mastering Data and Resources in SwiftUI


Hello Swift explorers! Today, we're diving into the world of lists, string processing, and how to make your app react to launch events. Let's get started!

The Power of Lists: Displaying Data Dynamically

The List view is essential for displaying collections of data in a scrollable, organized manner.

Example: Basic List of Strings

import SwiftUI

struct ListDemo: View {
    let words = ["Swift", "SwiftUI", "Xcode", "iOS"]

    var body: some View {
        List(words, id: \.self) { word in
            Text(word)
        }
    }
}

struct ListDemo_Previews: PreviewProvider {
    static var previews: some View {
        ListDemo()
    }
}

Visual Representation:

  • List(words, id: \.self): Creates a list from the words array, using the string itself as the unique identifier.

Treasure Hunting: Loading Resources from Your App Bundle

Your app bundle can contain various resources like text files, images, and more.

Example: Loading a Text File

import SwiftUI

struct ResourceLoading: View {
    @State private var content = ""

    var body: some View {
        Text(content)
            .onAppear(perform: loadFile)
            .padding()
    }

    func loadFile() {
        if let fileURL = Bundle.main.url(forResource: "words", withExtension: "txt") {
            do {
                content = try String(contentsOf: fileURL)
            } catch {
                content = "Error loading file: \(error.localizedDescription)"
            }
        } else {
            content = "File not found."
        }
    }
}

struct ResourceLoading_Previews: PreviewProvider {
    static var previews: some View {
        ResourceLoading()
    }
}

Visual Representation:

  • Bundle.main.url(forResource:withExtension:): Locates the file in the app bundle.
  • String(contentsOf:): Loads the file's content into a string.
  • .onAppear(perform:): Executes loadFile() when the view appears.

String Wizardry: Working with Strings

Swift provides powerful methods for manipulating strings.

Example: String Manipulation

import SwiftUI

struct StringManipulation: View {
    let text = "SwiftUI is Awesome!"

    var body: some View {
        VStack {
            Text("Original: \(text)")
            Text("Uppercase: \(text.uppercased())")
            Text("Contains 'Awesome': \(text.contains("Awesome"))")
            Text("Prefix 'Swift': \(text.hasPrefix("Swift"))")
        }
        .padding()
    }
}

struct StringManipulation_Previews: PreviewProvider {
    static var previews: some View {
        StringManipulation()
    }
}

Visual Representation:

  • .uppercased(): Converts the string to uppercase.
  • .contains(): Checks if the string contains a substring.
  • .hasPrefix(): Checks if the string starts with a prefix.

Word Hoarding: Adding to a List of Words

Let's combine lists and string manipulation to add words dynamically.

Example: Adding Words to a List

import SwiftUI

struct WordList: View {
    @State private var words = ["Swift", "SwiftUI"]
    @State private var newWord = ""

    var body: some View {
        VStack {
            TextField("Enter a word", text: $newWord)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()

            Button("Add Word") {
                if !newWord.isEmpty {
                    words.append(newWord)
                    newWord = ""
                }
            }
            .padding()

            List(words, id: \.self) { word in
                Text(word)
            }
        }
    }
}

struct WordList_Previews: PreviewProvider {
    static var previews: some View {
        WordList()
    }
}

Visual Representation:

  • TextField: Allows the user to enter a new word.
  • Button: Adds the new word to the words array.

Launch Sequence: Running Code When Our App Launches

You can execute code when your app launches using the onAppear modifier or by overriding the init() method of your main view.

Example: Running Code on App Launch

import SwiftUI

struct LaunchDemo: View {
    init() {
        print("App Launched!")
    }

    var body: some View {
        Text("Launch Demo")
    }
}

struct LaunchDemo_Previews: PreviewProvider {
    static var previews: some View {
        LaunchDemo()
    }
}

Console Output:

App Launched!
  • init(): The initializer is called when the view is created.

Word Police: Validating Words with UITextChecker

UITextChecker can be used to validate words and check for spelling errors.

Example: Validating Words

import SwiftUI
import UIKit

struct WordValidation: View {
    let textChecker = UITextChecker()
    let word = "SwiftUI"
    @State private var isValid = false

    var body: some View {
        Text("Word: \(word)")
        Text("Valid: \(isValid ? "Yes" : "No")")
        .onAppear(perform: checkWord)
    }

    func checkWord() {
        let range = NSRange(location: 0, length: word.utf16.count)
        let misspelledRange = textChecker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
        isValid = misspelledRange.location == NSNotFound
    }
}

struct WordValidation_Previews: PreviewProvider {
    static var previews: some View {
        WordValidation()
    }
}

Visual Representation:

  • UITextChecker: Checks for misspelled words.
  • rangeOfMisspelledWord: Returns the range of the misspelled word, or NSNotFound if the word is valid.

🔥 Conclusion

Day 16 has been packed with lists, resource loading, string manipulation, and app lifecycle management. Keep building, and you'll be creating more dynamic and feature-rich SwiftUI apps!


Follow me on Linkedin: igatitech 🚀🚀🚀

Comments

Popular posts from this blog

30 Days of SwiftUI — Day 1: Getting Started with SwiftUI

30 Days of SwiftUI Learning Journey: From Zero to Hero!

30 Days of SwiftUI - Day 11: Building Interactive SwiftUI Apps