Slide 1

Slide 1 text

Peter Friese, Developer Relations Engineer, Google Building Reusable SwiftUI Components @peterfriese SwiftConf 2023, Cologne

Slide 2

Slide 2 text

Peter Friese, Developer Relations Engineer, Google Building Reusable SwiftUI Components @peterfriese SwiftConf 2023, Cologne

Slide 3

Slide 3 text

Peter Friese Developer Relations Engineer Google

Slide 4

Slide 4 text

Peter Friese, Developer Relations Engineer, Google Building Reusable SwiftUI Components SwiftConf 2023, Cologne Why this talk? @peterfriese

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

Help developers succeed by making it easy to build and grow apps

Slide 9

Slide 9 text

 +

Slide 10

Slide 10 text

Books?

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

Subscribe for 20% off

Slide 13

Slide 13 text

Techniques for composing views Building a simple component Configuring views Styling views Distributing views

Slide 14

Slide 14 text

Building a simple component

Slide 15

Slide 15 text

Building a simple component app

Slide 16

Slide 16 text

import SwiftUI struct ContentView: View { var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } }

Slide 17

Slide 17 text

import SwiftUI struct ContentView: View { var body: some View { HStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } }

Slide 18

Slide 18 text

import SwiftUI struct ContentView: View { var body: some View { List(0 !!" 5) { item in HStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } }

Slide 19

Slide 19 text

import SwiftUI struct ContentView: View { var body: some View { List(0 !!" 5) { item in HStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } } } }

Slide 20

Slide 20 text

import SwiftUI struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in HStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text(user.fullName) } } } }

Slide 21

Slide 21 text

import SwiftUI struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in HStack { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) Text(user.fullName) } } } }

Slide 22

Slide 22 text

import SwiftUI struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in HStack { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack { Text(user.fullName) Text(user.affiliation) } } } } }

Slide 23

Slide 23 text

import SwiftUI struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) Text(user.affiliation) } } } } }

Slide 24

Slide 24 text

import SwiftUI struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } } } }

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

Move to file Extract Subview Extract to local subview (property) Extract to local subview (function)

Slide 27

Slide 27 text

Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } } } } ♻ Extract Subview

Slide 28

Slide 28 text

Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in ExtractedView() } } } struct ExtractedView: View { var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation)

Slide 29

Slide 29 text

Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in ExtractedView() } } } struct ExtractedView: View { var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation)

Slide 30

Slide 30 text

Dear Apple… Make Extract to Subview work all of the time

Slide 31

Slide 31 text

Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in ExtractedView() } } } struct ExtractedView: View { var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) ♻ Rename

Slide 32

Slide 32 text

Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView() } } } struct AvatarView: View { var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation)

Slide 33

Slide 33 text

❌ Cannot find ‘user’ in scope ❌ Cannot find ‘user’ in scope ❌ Cannot find ‘user’ in scope Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView() } } } struct AvatarView: View { var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation)

Slide 34

Slide 34 text

❌ Cannot find ‘user’ in scope ❌ Cannot find ‘user’ in scope Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView() } } } struct AvatarView: View { var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) var user: User

Slide 35

Slide 35 text

❌ Cannot find ‘user’ in scope ❌ Cannot find ‘user’ in scope Extract Subview struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(user: user) } } } struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline)

Slide 36

Slide 36 text

Dear Apple… Make Extract to Subview work all of the time Extract to Subview: handle dependent properties

Slide 37

Slide 37 text

Move to file Extract Subview Extract to local subview (property) Extract to local subview (function)

Slide 38

Slide 38 text

Move to file struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(user: user) } } } struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) ♻ Move to file

Slide 39

Slide 39 text

Move to file New SwiftUI File

Slide 40

Slide 40 text

Move to file Make sure to use type name

Slide 41

Slide 41 text

Move to file import SwiftUI struct AvatarView: View { var body: some View { Text("Hello, World!") } } #Preview { AvatarView() }

Slide 42

Slide 42 text

❌ Missing argument for parameter 'user' in call Move to file struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } } } #Preview { AvatarView() Need to fix the preview

Slide 43

Slide 43 text

❌ Missing argument for parameter 'user' in call Move to file struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } } } #Preview { AvatarView(user: User.sample)

Slide 44

Slide 44 text

Dear Apple… Make Extract to Subview work all of the time Extract to Subview: handle dependent properties Add Extract to File

Slide 45

Slide 45 text

struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } } } #Preview { AvatarView(user: User.sample) } What’s this?!

Slide 46

Slide 46 text

struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } } } #Preview { AvatarView(user: User.sample) }

Slide 47

Slide 47 text

SwiftUI Layout Behaviour Building layouts with stack views https://apple.co/448CaWL Created by redemption_art from the Noun Project Created by redemption_art from the Noun Project Expanding Hugging

Slide 48

Slide 48 text

HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } Created by redemption_art from the Noun Project Text is a content-hugging view

Slide 49

Slide 49 text

HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } Created by redemption_art from the Noun Project VStack is a content-hugging view

Slide 50

Slide 50 text

HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } Image is an expanding view Created by redemption_art from the Noun Project … but we explicitly constrained it

Slide 51

Slide 51 text

HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } HStack is a content-hugging view Created by redemption_art from the Noun Project

Slide 52

Slide 52 text

HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } Spacer() } Spacer is an expanding view Created by redemption_art from the Noun Project

Slide 53

Slide 53 text

Move to file Extract Subview Extract to local subview (property) Extract to local subview (function)

Slide 54

Slide 54 text

Extract to local subview (property) struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } Spacer() } } } ♻ Extract to local subview

Slide 55

Slide 55 text

Extract to local subview (property) struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.affiliation) .font(.subheadline) } var titleLabel: some View { } Text(user.fullName) .font(.headline)

Slide 56

Slide 56 text

Extract to local subview (property) struct AvatarView: View { var user: User var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.affiliation) .font(.subheadline) } var titleLabel: some View { } Text(user.fullName) .font(.headline)

Slide 57

Slide 57 text

Extract to local subview (property) struct AvatarView: View { var user: User var titleLabel: some View { Text(user.fullName) .font(.headline) } var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.affiliation) .font(.subheadline) } Spacer() titleLabel

Slide 58

Slide 58 text

Dear Apple… Make Extract to Subview work all of the time Extract to Subview: handle dependent properties Add Extract to File Add Extract to local Subview

Slide 59

Slide 59 text

Move to file Extract Subview Extract to local subview (property) Extract to local subview (function)

Slide 60

Slide 60 text

Extract to local subview (function) var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { titleLabel Text("\(Image(systemName: "graduationcap")) \(user.jobtitle)") .font(.subheadline) Text("\(Image(systemName: "building.2")) \(user.affiliation)") .font(.subheadline) } Spacer() } } struct AvatarView: View { var user: User var titleLabel: some View {!!#}

Slide 61

Slide 61 text

Extract to local subview (function) struct AvatarView: View { var user: User var titleLabel: some View {!!#} var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { titleLabel Text("\(Image(systemName: "graduationcap")) \(user.jobtitle)") .font(.subheadline) Text("\(Image(systemName: "building.2")) \(user.affiliation)") func detailsLabel(_ text: String, systemName: String) !$ some View { }

Slide 62

Slide 62 text

Extract to local subview (function) struct AvatarView: View { var user: User var titleLabel: some View {!!#} var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { titleLabel Text("\(Image(systemName: "building.2")) \(user.affiliation)") func detailsLabel(_ text: String, systemName: String) !$ some View { } Text("\(Image(systemName: "graduationcap")) \(user.jobtitle)") .font(.subheadline)

Slide 63

Slide 63 text

Extract to local subview (function) struct AvatarView: View { var user: User var titleLabel: some View {!!#} var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { titleLabel Text("\(Image(systemName: "building.2")) \(user.affiliation)") func detailsLabel(_ text: String, systemName: String) !$ some View { } Text("\(Image(systemName: "graduationcap")) \(user.jobtitle)") .font(.subheadline)

Slide 64

Slide 64 text

Extract to local subview (function) struct AvatarView: View { var user: User var titleLabel: some View {!!#} var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { titleLabel Text("\(Im func detailsLabel(_ text: String, systemName: String) !$ some View { } Text("\(Image(systemName: .font(.subheadline) "graduationcap")) \(user.jobtitle)") "\(systemName)")) \(text)") Text("\(Image(systemName: "building.2")) \(user.affiliation)")

Slide 65

Slide 65 text

Extract to local subview (function) struct AvatarView: View { var user: User var titleLabel: some View {!!#} func detailsLabel(_ text: String, systemName: String) !$ some View { Text("\(Image(systemName: "\(systemName)")) \(text)") .font(.subheadline) } var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { titleLabel Text("\(Image(systemName: "building.2")) \(user.affiliation)") .font(.subheadline) detailsLabel(user.jobtitle, systemName: "graduationcap") detailsLabel(user.affiliation, systemName: "building.2")

Slide 66

Slide 66 text

Extract to local subview (function) struct AvatarView: View { var user: User var titleLabel: some View {!!#} func detailsLabel(_ text: String, systemName: String) !$ some View { Text("\(Image(systemName: "\(systemName)")) \(text)") .font(.subheadline) } var body: some View { HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { titleLabel detailsLabel(user.jobtitle, systemName: "graduationcap") detailsLabel(user.affiliation, systemName: "building.2") }

Slide 67

Slide 67 text

Techniques for composing views Building a simple component Configuring views Styling views Distributing views

Slide 68

Slide 68 text

Techniques for composing views

Slide 69

Slide 69 text

View body import SwiftUI struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in HStack(alignment: .top) { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { Text(user.fullName) .font(.headline) Text(user.affiliation) .font(.subheadline) } } } } }

Slide 70

Slide 70 text

Local properties View body struct AvatarView: View { var user: User var titleLabel: some View { Text(user.fullName) .font(.headline) } var body: some View { !!# titleLabel !!# } }

Slide 71

Slide 71 text

Local properties View body Local functions struct AvatarView: View { var user: User func detailsLabel(_ text: String, systemName: String) !$ some View { Text("\(Image(systemName: "\(systemName)")) \(text)") .font(.subheadline) } var body: some View { !!# detailsLabel(user.jobtitle, systemName: "graduationcap") detailsLabel(user.affiliation, systemName: “building.2") !!# } }

Slide 72

Slide 72 text

Local properties View body Local functions View Builders

Slide 73

Slide 73 text

View Builders @ViewBuilder usage explained with code examples (SwiftLee) https://bit.ly/44bp37t The @ViewBuilder attribute is one of the few result builders available for you to use in SwiftUI. You typically use it to create child views for a specific SwiftUI view in a readable way without having to use any return keywords. “

Slide 74

Slide 74 text

View Builders struct AvatarView: View { var user: User var titleLabel: some View { Text(user.fullName) .font(.headline) } func detailsLabel(_ text: String, systemName: String) !$ some View { Text("\(Image(systemName: "\(systemName)")) \(text)") .font(.subheadline) } var body: some View { !!# detailsLabel(user.jobtitle, systemName: "graduationcap") detailsLabel(user.affiliation, systemName: “building.2") !!# } Why no @ViewBuilder?

Slide 75

Slide 75 text

View Builders struct AvatarView: View { var user: User var hero: some View { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } var body: some View { HStack(alignment: .top) { hero VStack(alignment: .leading) {!!# } } } }

Slide 76

Slide 76 text

View Builders struct AvatarView: View { var isRound = true var user: User var hero: some View { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } var body: some View { HStack(alignment: .top) { hero VStack(alignment: .leading) {!!# } } } }

Slide 77

Slide 77 text

❌ Branches have mismatching types 'some View' View Builders struct AvatarView: View { var isRound = true var user: User var hero: some View { if isRound { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } else { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) } } var body: some View { Self.clipShape(_:style:) Self.frame(width:height:alignment:)

Slide 78

Slide 78 text

View Builders struct AvatarView: View { var isRound = true var user: User var hero: some View { if isRound { AnyView { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } } else { AnyView { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) } AnyView erases the view’s type information

Slide 79

Slide 79 text

View Builders struct AvatarView: View { var isRound = true var user: User var hero: some View { if isRound { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } else { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) } } @ViewBuilder @ViewBuilder keeps the type information

Slide 80

Slide 80 text

View Builders How to avoid using AnyView in SwiftUI (Tanaschita.com) ViewBuilder vs. AnyView (Alexito's World) https://bit.ly/45kVOQI https://bit.ly/3OUbViE Use @ViewBuilder if you want to return structurally different views from a property / function. “

Slide 81

Slide 81 text

Techniques for composing views Building a simple component Configuring views Styling views Distributing views

Slide 82

Slide 82 text

Configuring views

Slide 83

Slide 83 text

Configuring views struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(isRound: true, user: user) } } } Let’s turn this into a view modifier : properties

Slide 84

Slide 84 text

Enum for the shape enum AvatarImageShape { case round case rectangle }

Slide 85

Slide 85 text

Environment Key Enum for the shape struct AvatarImageShapeKey: EnvironmentKey { static var defaultValue: AvatarImageShape = .round } enum AvatarImageShape { case round case rectangle }

Slide 86

Slide 86 text

Environment Key Enum for the shape Extend Environment struct AvatarImageShapeKey: EnvironmentKey { static var defaultValue: AvatarImageShape = .round } enum AvatarImageShape { case round case rectangle } extension EnvironmentValues { var avatarImageShape: AvatarImageShape { get { self[AvatarImageShapeKey.self] } set { self[AvatarImageShapeKey.self] = newValue } } }

Slide 87

Slide 87 text

Environment Key Enum for the shape Extend Environment View modifier struct AvatarImageShapeKey: EnvironmentKey { static var defaultValue: AvatarImageShape = .round } enum AvatarImageShape { case round case rectangle } extension EnvironmentValues { var avatarImageShape: AvatarImageShape { get { self[AvatarImageShapeKey.self] } set { self[AvatarImageShapeKey.self] = newValue } } } extension View { func avatarImageShape(_ imageShape: AvatarImageShape) !$ some View { environment(\.avatarImageShape, imageShape) } }

Slide 88

Slide 88 text

Environment Key Enum for the shape Extend Environment View modifier Update view code struct AvatarView: View { var isRound = true var user: User @ViewBuilder var hero: some View { if isRound { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } else { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) } } !!# } var isRound = true

Slide 89

Slide 89 text

Environment Key Enum for the shape Extend Environment View modifier Update view code struct AvatarView: View { var user: User @ViewBuilder var hero: some View { if isRound { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } else { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) } } !!# } var isRound = true @Environment(\.avatarImageShape) var imageShape

Slide 90

Slide 90 text

Environment Key Enum for the shape Extend Environment View modifier Update view code struct AvatarView: View { var user: User @ViewBuilder var hero: some View { if { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) .clipShape(Circle(), style: FillStyle()) } else { Image(user.profileImageName) .resizable() .aspectRatio(contentMode: .fit) .frame(height: 75) } } !!# } @Environment(\.avatarImageShape) var imageShape imageShape !% .round

Slide 91

Slide 91 text

Environment Key Enum for the shape Extend Environment View modifier Update view code Usage at the call site struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(user: user) .avatarImageShape(.rectangle) } } }

Slide 92

Slide 92 text

Environment Key Enum for the shape Extend Environment View modifier Update view code Usage at the call site struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(user: user) .avatarImageShape(.rectangle) } } } struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(user: user) } .avatarImageShape(.rectangle) } }

Slide 93

Slide 93 text

Environment Key Enum for the shape Extend Environment View modifier Update view code Usage at the call site struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(user: user) } .avatarImageShape(.rectangle) } } struct ContentView: View { @State var users = User.samples var body: some View { List(users) { user in AvatarView(user: user) .avatarImageShape( user.isTalking ? .round : .rectangle) } .avatarImageShape(.rectangle) } }

Slide 94

Slide 94 text

Configuring views struct ContentView: View { var body: some View { AvatarView(user: User.sample) .onEditProfile { print("onEditProfile triggered") } } } Let’s register an action handler : action handlers

Slide 95

Slide 95 text

Environment Key struct AvatarEditProfileHandler: EnvironmentKey { static var defaultValue: (() !$ Void)? }

Slide 96

Slide 96 text

Extend Environment Environment Key struct AvatarEditProfileHandler: EnvironmentKey { static var defaultValue: (() !$ Void)? } extension EnvironmentValues { var editProfileHandler: (() !$ Void)? { get { self[AvatarEditProfileHandler.self] } set { self[AvatarEditProfileHandler.self] = newValue } } }

Slide 97

Slide 97 text

Extend Environment Environment Key View modifier struct AvatarEditProfileHandler: EnvironmentKey { static var defaultValue: (() !$ Void)? } extension EnvironmentValues { var editProfileHandler: (() !$ Void)? { get { self[AvatarEditProfileHandler.self] } set { self[AvatarEditProfileHandler.self] = newValue } } } extension View { public func onEditProfile(editProfileHandler: @escaping () !$ Void) !$ some View { environment(\.editProfileHandler, editProfileHandler) } }

Slide 98

Slide 98 text

Extend Environment Environment Key View modifier Update view code struct AvatarView: View { @Environment(\.avatarImageShape) var imageShape !!# } } } var user: User @ViewBuilder var hero: some View { !!# } var body: some View { HStack(alignment: .top) { hero

Slide 99

Slide 99 text

Extend Environment Environment Key View modifier Update view code struct AvatarView: View { @Environment(\.avatarImageShape) var imageShape !!# } } } var user: User @ViewBuilder var hero: some View { !!# } var body: some View { HStack(alignment: .top) { hero @Environment(\.editProfileHandler) var editProfileHandler

Slide 100

Slide 100 text

Extend Environment Environment Key View modifier Update view code struct AvatarView: View { @Environment(\.avatarImageShape) var imageShape var user: User @ViewBuilder var hero: some View { !!# } var body: some View { HStack(alignment: .top) { hero @Environment(\.editProfileHandler) var editProfileHandler !!# } } } .onTapGesture { if let editProfileHandler { editProfileHandler() } }

Slide 101

Slide 101 text

Extend Environment Environment Key View modifier Update view code Usage at the call site struct ContentView: View { @State var isEditing = false var body: some View { AvatarView(user: User.sample) .padding() .onEditProfile { isEditingProfile.toggle() } .sheet(isPresented: $isEditing) { !!# } } }

Slide 102

Slide 102 text

Techniques for composing views Building a simple component Configuring views Styling views Distributing views

Slide 103

Slide 103 text

Styling views

Slide 104

Slide 104 text

Styling views View styles (Apple docs) Styling SwiftUI Views (peterfriese.dev) https://bit.ly/3DYKmyu https://bit.ly/3qFbJKC SwiftUI defines built-in styles for certain kinds of views and automatically selects the appropriate style for a particular presentation context. […] You can override the automatic style by using one of the style view modifiers. These modifiers typically propagate throughout a container view, so that you can wrap a view hierarchy in a style modifier to affect all the views of the given type within the hierarchy. “

Slide 105

Slide 105 text

Styling views struct StylingExamples: View { var body: some View { Button("Unstyled button") { } Button("Bordered button") { } .buttonStyle(.bordered) Button("Bordered prominent button") { } .buttonStyle(.borderedProminent) Button("Borderless button") { } .buttonStyle(.borderless) Button("Plain button") { } .buttonStyle(.plain) Button("Automatic button") { } .buttonStyle(.automatic) } } : Buttons

Slide 106

Slide 106 text

Styling views struct ToggleStyleDemoView: View { @State var isOn = true var body: some View { VStack { Toggle(isOn: $isOn) { Text("Custom toggle style") } .toggleStyle(.reminder) Toggle(isOn: $isOn) { Text("Default toggle style") } } } } : a custom Toggle style

Slide 107

Slide 107 text

Style protocol struct ReminderToggleStyle: ToggleStyle { func makeBody(configuration: Configuration) !$ some View { HStack { Image(systemName: configuration.isOn ? "largecircle.fill.circle" : "circle") .resizable() .frame(width: 24, height: 24) .foregroundColor(configuration.isOn ? .accentColor : .gray) .onTapGesture { configuration.isOn.toggle() } configuration.label } } }

Slide 108

Slide 108 text

Style protocol struct ReminderToggleStyle: ToggleStyle { func makeBody(configuration: Configuration) !$ some View { HStack { Image(systemName: configuration.isOn ? "largecircle.fill.circle" : "circle") .resizable() .frame(width: 24, height: 24) .foregroundColor(configuration.isOn ? .accentColor : .gray) .onTapGesture { configuration.isOn.toggle() } configuration.label } } }

Slide 109

Slide 109 text

Style protocol struct ReminderToggleStyle: ToggleStyle { func makeBody(configuration: Configuration) !$ some View { HStack { Image(systemName: configuration.isOn ? "largecircle.fill.circle" : "circle") .resizable() .frame(width: 24, height: 24) .foregroundColor(configuration.isOn ? .accentColor : .gray) .onTapGesture { configuration.isOn.toggle() } configuration.label } } }

Slide 110

Slide 110 text

Style protocol struct ReminderToggleStyle: ToggleStyle { func makeBody(configuration: Configuration) !$ some View { HStack { Image(systemName: configuration.isOn ? "largecircle.fill.circle" : "circle") .resizable() .frame(width: 24, height: 24) .foregroundColor(configuration.isOn ? .accentColor : .gray) .onTapGesture { configuration.isOn.toggle() } configuration.label } } }

Slide 111

Slide 111 text

Define style shortcut Style protocol ? .accentColor : .gray) .onTapGesture { configuration.isOn.toggle() } configuration.label } } } extension ToggleStyle where Self !% ReminderToggleStyle { static var reminder: ReminderToggleStyle { ReminderToggleStyle() } }

Slide 112

Slide 112 text

Define style shortcut Style protocol Apply the style extension ToggleStyle where Self !% ReminderToggleStyle { static var reminder: ReminderToggleStyle { ReminderToggleStyle() } } struct ToggleStyleDemoView: View { @State var isOn = true var body: some View { VStack { Toggle(isOn: $isOn) { Text("Custom toggle style") } .toggleStyle(.reminder) } } }

Slide 113

Slide 113 text

Styling views Audience of this talk

Slide 114

Slide 114 text

Styling views View styles (Apple docs) Styling SwiftUI Views (peterfriese.dev) https://bit.ly/3DYKmyu https://bit.ly/3qFbJKC SwiftUI defines built-in styles for certain kinds of views and automatically selects the appropriate style for a particular presentation context. […] You can override the automatic style by using one of the style view modifiers. These modifiers typically propagate throughout a container view, so that you can wrap a view hierarchy in a style modifier to affect all the views of the given type within the hierarchy. “ Context: * Platform * Container * Use case Propagation: * Design system

Slide 115

Slide 115 text

No content

Slide 116

Slide 116 text

Create a configuration struct AvatarStyleConfiguration { let title: Title struct Title: View { let underlyingTitle: AnyView init(_ title: some View) { self.underlyingTitle = AnyView(title) } var body: some View { underlyingTitle } }

Slide 117

Slide 117 text

Create a configuration struct Title: View { let underlyingTitle: AnyView init(_ title: some View) { self.underlyingTitle = AnyView(title) } var body: some View { underlyingTitle } } let subTitle: SubTitle struct SubTitle: View { let underlyingSubTitle: AnyView init(_ subTitle: some View) { self.underlyingSubTitle = AnyView(subTitle) } var body: some View { underlyingSubTitle } }

Slide 118

Slide 118 text

Create a configuration struct SubTitle: View { let underlyingSubTitle: AnyView init(_ subTitle: some View) { self.underlyingSubTitle = AnyView(subTitle) } var body: some View { underlyingSubTitle } } let image: Image init(title: Title, subTitle: SubTitle, image: Image) { self.title = title self.subTitle = subTitle self.image = image } }

Slide 119

Slide 119 text

Define a style protocol Create a configuration let image: Image init(title: Title, subTitle: SubTitle, image: Image) { self.title = title self.subTitle = subTitle self.image = image } } protocol AvatarStyle { associatedtype Body: View @ViewBuilder func makeBody(configuration: Configuration) !$ Body typealias Configuration = AvatarStyleConfiguration }

Slide 120

Slide 120 text

Define a style protocol Create a configuration Set up environment protocol AvatarStyle { associatedtype Body: View @ViewBuilder func makeBody(configuration: Configuration) !$ Body typealias Configuration = AvatarStyleConfiguration } struct AvatarStyleKey: EnvironmentKey { static var defaultValue: any AvatarStyle = DefaultAvatarStyle() } extension EnvironmentValues { var avatarStyle: any AvatarStyle { get { self[AvatarStyleKey.self] } set { self[AvatarStyleKey.self] = newValue } } }

Slide 121

Slide 121 text

Define a style protocol Create a configuration Set up environment struct AvatarStyleKey: EnvironmentKey { static var defaultValue: any AvatarStyle = DefaultAvatarStyle() } extension EnvironmentValues { var avatarStyle: any AvatarStyle { get { self[AvatarStyleKey.self] } set { self[AvatarStyleKey.self] = newValue } } } extension View { func avatarStyle(_ style: some AvatarStyle) !$ some View { environment(\.avatarStyle, style) } }

Slide 122

Slide 122 text

Define a style protocol Create a configuration Set up environment Implement style struct DefaultAvatarStyle: AvatarStyle { func makeBody(configuration: Configuration) !$ some View { HStack(alignment: .top) { configuration.image .resizable() .aspectRatio(contentMode: .fit) .frame(width: 50, height: 50, alignment: .center) .clipShape(Circle(), style: FillStyle()) VStack(alignment: .leading) { configuration.title .font(.headline) configuration.subTitle .font(.subheadline) } Spacer() } } }

Slide 123

Slide 123 text

Define a style protocol Create a configuration Set up environment Implement style Update view code struct AvatarView: View { @Environment(\.avatarImageShape) var imageShape @Environment(\.editProfileHandler) var editProfileHandler @Environment(\.avatarStyle) var style var title: String var subTitle: String var imageName: String init(_ title: String, subTitle: String, image name: String) { self.title = title self.subTitle = subTitle self.imageName = name }

Slide 124

Slide 124 text

Define a style protocol Create a configuration Set up environment Implement style Update view code var title: String var subTitle: String var imageName: String init(_ title: String, subTitle: String, image name: String) { self.title = title self.subTitle = subTitle self.imageName = name } var body: some View { let configuration = AvatarStyleConfiguration( title: .init(Text(title)), subTitle: .init(Text(subTitle)), image: .init(imageName)) AnyView( style.makeBody(configuration: configuration) ) } }

Slide 125

Slide 125 text

Define a style protocol Create a configuration Set up environment Implement style Update view code var title: String var subTitle: String var imageName: String init(_ title: String, subTitle: String, image name: String) { self.title = title self.subTitle = subTitle self.imageName = name } var body: some View { let configuration = AvatarStyleConfiguration( title: .init(Text(title)), subTitle: .init(Text(subTitle)), image: .init(imageName)) AnyView( style.makeBody(configuration: configuration) ) } }

Slide 126

Slide 126 text

Define a style protocol Create a configuration Set up environment Implement style Update view code Usage at the call site struct ContentView: View { @State var users = User.samples @State var isProfileShowing = false var body: some View { List(users) { user in AvatarView(user.fullName, subTitle: user.affiliation, image: user.profileImageName) .avatarStyle(.automatic) } } }

Slide 127

Slide 127 text

struct ContentView: View { @State var users = User.samples @State var isProfileShowing = false var body: some View { List(users) { user in AvatarView(user.fullName, subTitle: user.affiliation, image: user.profileImageName) .avatarStyle(.automatic) } } }

Slide 128

Slide 128 text

No content

Slide 129

Slide 129 text

No content

Slide 130

Slide 130 text

Implement style struct ProfileAvatarStyle: AvatarStyle { func makeBody(configuration: Configuration) !$ some View { VStack(alignment: .center) { configuration.image .resizable() .aspectRatio(contentMode: .fill) .frame(width: 50, height: 50, alignment: .center) .clipShape(Circle(), style: FillStyle()) configuration.title .font(.headline) configuration.subTitle .font(.subheadline) } } }

Slide 131

Slide 131 text

Define style shortcut Implement style .resizable() .aspectRatio(contentMode: .fill) .frame(width: 50, height: 50, alignment: .center) .clipShape(Circle(), style: FillStyle()) configuration.title .font(.headline) configuration.subTitle .font(.subheadline) } } } extension AvatarStyle where Self !% ProfileAvatarStyle { static var profile: Self { .init() } }

Slide 132

Slide 132 text

Define style shortcut Implement style Usage at the call site AvatarView(user.fullName, subTitle: user.affiliation, image: user.profileImageName) .avatarStyle(.profile)

Slide 133

Slide 133 text

AvatarView(user.fullName, subTitle: user.affiliation, image: user.profileImageName) .avatarStyle(.profile)

Slide 134

Slide 134 text

Techniques for composing views Building a simple component Configuring views Styling views Distributing views

Slide 135

Slide 135 text

Distributing views

Slide 136

Slide 136 text

File > New Package Add to the current project

Slide 137

Slide 137 text

♻ Extract to package

Slide 138

Slide 138 text

Dear Apple… Make Extract to Subview work all of the time Extract to Subview: handle dependent properties Add Extract to File Add Extract to local Subview Add Extract to Package

Slide 139

Slide 139 text

Xcode Component Library

Slide 140

Slide 140 text

No content

Slide 141

Slide 141 text

Register views, view modifiers, and styles public struct AvatarView_Library: LibraryContentProvider { public var views: [LibraryItem] { [ LibraryItem(AvatarView("Peter", subTitle: "Google", image: ""), title: "AvatarView", category: .control) ] } public func modifiers(base: AvatarView) !$ [LibraryItem] { [ LibraryItem(base.avatarStyle(.profile), title: "Profile", category: .control) ] } }

Slide 142

Slide 142 text

#

Slide 143

Slide 143 text

Dear Apple… Make Extract to Subview work all of the time Extract to Subview: handle dependent properties Add Extract to File Add Extract to local Subview Add Extract to Package Rich previews for the Xcode Component Library

Slide 144

Slide 144 text

Distributing

Slide 145

Slide 145 text

No content

Slide 146

Slide 146 text

No content

Slide 147

Slide 147 text

No content

Slide 148

Slide 148 text

Resources Source Code YouTube series https://bit.ly/3n99fis https://bit.ly/building-swiftui-components Composable Styles (Moving Parts) https://bit.ly/47w7wJY

Slide 149

Slide 149 text

Resources Creating a Styleable Toggle SwiftUI Components Tutorial @ iOSDevUK https://bit.ly/3siupAk September 4th - 7th, 2023

Slide 150

Slide 150 text

Thanks!

Slide 151

Slide 151 text

Thanks! Peter Friese peterfriese.dev @peterfriese youtube.com/c/PeterFriese/ not-only-swift.peterfriese.dev/ @peterfriese@iosdev.space