Skip to content

Instantly share code, notes, and snippets.

@perlguy99
Last active March 4, 2020 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perlguy99/6141860dda753066e472c5648b6153c3 to your computer and use it in GitHub Desktop.
Save perlguy99/6141860dda753066e472c5648b6153c3 to your computer and use it in GitHub Desktop.
SwiftUI_Extensions

SwiftUI Extensions

Using ForEach with raw values

(So we don't have to use id: .self)

Reference

extension ForEach where Data.Element: Hashable, ID == Data.Element, Content: View {
    init(values: Data, content: @escaping (Data.Element) -> Content) {
        self.init(values, id: \.self, content: content)
    }
}

Optional SwiftUI Views

Article

Configuring SwiftUI Views

Prefixing a view with an icon, easily...

Article

extension View {
    func prefixedWithIcon(named name: String) -> some View {
        HStack {
            Image(systemName: name)
            self
        }
    }
}

Then, to use...

    var body: some View {
        Form {
            ...
            TextField("Username", text: $username)
                .prefixedWithIcon(named: "person.circle.fill")
            TextField("Email", text: $email)
                .prefixedWithIcon(named: "envelope.circle.fill")
            ...
        }
    }

View Modifiers

struct Validation<Value>: ViewModifier {
    var value: Value
    var validator: (Value) -> Bool

    func body(content: Content) -> some View {
        // Here we use Group to perform type erasure, to give our
        // method a single return type, as applying the 'border'
        // modifier causes a different type to be returned:
        Group {
            if validator(value) {
                content.border(Color.green)
            } else {
                content
            }
        }
    }
}

Then, to use...

TextField("Username", text: $username)
    .modifier(Validation(value: username) { name in
        name.count > 4
    })
    .prefixedWithIcon(named: "person.circle.fill")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment