Swift Lessons

New ScrollView iOS 17 SwiftUI

The scroll view displays its content within the scrollable content region. As the user performs platform-appropriate scroll gestures, the scroll view adjusts what portion of the underlying content is visible. ScrollView can scroll horizontally, vertically, or both, but does not provide zooming functionality.

import SwiftUI

struct CardsView: View {
    
    var body: some View {
        content
            .navigationBarTitleDisplayMode(.inline)
    }
}

private extension CardsView {
    
    var content: some View {
        ScrollView {
            LazyVStack {
                ForEach(1..<20) { _ in
                    Color.purple
                        .frame(height: 120)
                        .cornerRadius(20)
                }
            }
        }
        .scrollIndicators(.hidden)
        .safeAreaInset(edge: .top) {
            ScrollView(.horizontal) {
                LazyHStack {
                    ForEach(1..<10) { _ in
                        Color.blue
                            .frame(height: 80)
                            .cornerRadius(20)
                            .containerRelativeFrame(.horizontal,
                                                    count: 5,
                                                    span: 2,
                                                    spacing: 8)
                    }
                }
                .scrollTargetLayout()
            }
            .scrollTargetBehavior(.viewAligned)
            .scrollIndicators(.hidden)
            .padding(.vertical, 8)
            .fixedSize(horizontal: false, vertical: true)
            .background(.thinMaterial)
        }
        .safeAreaPadding(.horizontal)
    }
}

#Preview {
    CardsView()
}

code on my GitHub

How to add placeholder text to TextEditor in SwiftUI?

Built-in TextEditor does not have a placeholder. This is very easy to do.

import SwiftUI

struct TextEditorView: View {
    
    @Binding var comment: String
    
    init(comment: Binding<String>) {
        self._comment = comment
        
        UITextView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            placeholder
                .padding(.leading, 10)
                .padding(.top, 7)
            textEditor
        }
        .padding()
        .background(Color(.sRGB, red: 0.85, green: 0.85, blue: 0.85, opacity: 1))
        .cornerRadius(10)
        .overlay(border)
    }
}

// MARK: - Views
private extension TextEditorView {
    
    var placeholder: some View {
        Text(comment.isEmpty ? "Please write your comment" : "")
            .foregroundColor(.gray)
            .font(.system(size: 14, weight: .regular, design: .default))
    }
    
    var textEditor: some View {
        TextEditor(text: $comment)
            .background(Color.clear)
            .foregroundColor(Color.black)
            .font(.system(size: 14, weight: .regular, design: .default))
            .frame(height: 80)
            .cornerRadius(10)
    }
    
    var border: some View {
        RoundedRectangle(cornerRadius: 10)
            .stroke(Color.gray, lineWidth: 1)
    }
}

File in my GitHub – link

Basics of Arrays

In swift, arrays are useful to store the same data type of multiple values in an ordered manner. In array, we can store the same value in multiple times at different positions based on our requirements.

In swift arrays, we can store any kind of elements like either strings or integers or other element types based on our requirements.

Empty arrays:

var array: [String] = [] // type annotation + array literal
var array = [String]() // invoking the [String] initializer
var array = Array() // without syntactic sugar

An array of string elements:

var names = ["Adam", "Danny", "Pavel"]

Array literals:

let arrayOfInt = [1, 3, 5]

Exponentiation

In Swift, we can exponentiate Doubles with the built-in pow() method:

pow(BASE, EXPONENT)

In the code below, the base (10) is set to the power of the exponent (2) :

let number = pow(10.0, 2.0) // Equals 100

Deleting a POD File

Sometimes it happens that the installed framework stops working correctly and causes errors. In this case, deleting the POD file and reinstalling it can help.

$ sudo gem install cocoapods-deintegrate cocoapods-clean
$ pod deintegrate
$ pod clean
$ rm Podfile

Random number generation

arc4random_uniform(someNumber: UInt32) -> UInt32

This gives you random integers in the range 0 to someNumber – 1.

The maximum value for UInt32 is 4,294,967,295.

let day = arc4random_uniform(31) + 1 // 1...31
let year = 2010 + arc4random_uniform(10) // random year

Property Observers

Property observers respond to changes to a property’s value.

var myProperty = 5 {
willSet {
print("Will set to \(newValue). It was previously \(myProperty)")
}
didSet {
print("Did set to \(myProperty). It was previously \(oldValue)")
}
}
myProperty = 6
// prints: Will set to 6, It was previously 5
// prints: Did set to 6. It was previously 5

Creating a Variable

Declare a new variable with var, followed by a name, type, and value:

var num: Int = 10
var str: String = "Hello World!"

Variables can have their values changed:
num = 20 // num now equals 20

Unless they’re defined with let:
let num: Int = 10 // num cannot change

Swift infers the type of variable, so you don’t always have to declare variable type:
var ten = 10 // num is an Int
var txt = "Hello!" // text is a String
var pi = 3.14 // pi is a Double
var floatPi: Float = 3.14 // floatPi is a Float