<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by gloomikon on Medium]]></title>
        <description><![CDATA[Stories by gloomikon on Medium]]></description>
        <link>https://medium.com/@gloomikon?source=rss-d3bcf152f392------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-Ny_CDtv7k62fQBytsXOCw.jpeg</url>
            <title>Stories by gloomikon on Medium</title>
            <link>https://medium.com/@gloomikon?source=rss-d3bcf152f392------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:11:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gloomikon/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reusable Paywall Components with SwiftUI]]></title>
            <link>https://medium.com/@gloomikon/reusable-paywalls-with-swiftui-c8242106dada?source=rss-d3bcf152f392------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8242106dada</guid>
            <category><![CDATA[paywall]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[swiftu]]></category>
            <dc:creator><![CDATA[gloomikon]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 17:23:59 GMT</pubDate>
            <atom:updated>2024-07-20T17:26:07.579Z</atom:updated>
            <content:encoded><![CDATA[<p>Subscriptions are the most popular monetization model in modern apps. Teams work hard to make their paywalls as attractive as possible, often conducting various A/B tests to find the most profitable screen design.</p><p>Developing new A/B tests quickly is crucial for both business and engineering teams. First, because time to market is essential — there might be valuable insights that need immediate testing. Second, because every hour and dollar spent creating another paywall is an hour and a dollar not spent on innovations (credit to <a href="https://www.linkedin.com/in/alex1ong/">Alex Ozun</a> for this thought).</p><p>Having developed numerous paywalls myself, I’d like to share my ideas on how we can deliver these tasks as quickly as possible while maintaining flexibility. This article will focus on the UI aspect, with implementation in SwiftUI. Even if paywalls aren’t your main interest, I believe you’ll find some useful techniques that can be applied to other problems as well.</p><blockquote><strong><em>Note:</em></strong><em> The project is available in the </em><a href="https://github.com/gloomikon/PaywallView"><em>GitHub repository</em></a><em>.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTZFKXuBDrpy8xjgr8uLtg.png" /><figcaption>Paywalls examples</figcaption></figure><p>Above are examples of paywalls from three different apps. Of course, there are many more variations. Some include animations, some have videos, some are scrollable, and others consist of several screens. However, in my experience, when it comes to A/B testing, not everything changes. Most likely, your team will develop a ‘skeleton’ that remains constant while the A/B tests focus on the appearance and content.</p><p>Here is an example of such a skeleton that is quite similar to the paywalls shown above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*55_50PQXYxqaScJnsMIVhw.png" /></figure><p>The goal I want to achieve is to create a component or system that allows us to focus solely on new elements when developing an A/B test, while extracting the unchangeable elements elsewhere. This system should also be configurable if needed.</p><p>To achieve this, the idea is to create a PaywallView that will take the content as an input (another view). The PaywallView will be responsible for the skeleton layout. We’ll start with something simple and increase the complexity as needed.</p><p>First, let’s create the components for PaywallView: the Header and Footer.</p><pre>struct Header: View {<br><br>    var body: some View {<br>        HStack {<br>            Button {<br>               // close<br>            } label: {<br>                Image(systemName: &quot;xmark&quot;)<br>                    .resizable()<br>                    .renderingMode(.template)<br>                    .frame(width: 16, height: 16)<br>            }<br><br>            Spacer()<br><br>            Button(&quot;Restore&quot;) {<br>                // restore<br>            }<br>        }<br>        .foregroundStyle(Color(.label))<br>        .padding(.horizontal, 18)<br>        .padding(.top, 2)<br>        .font(.footnote)<br>    }<br>}</pre><pre>struct Footer: View {<br><br>    var body: some View {<br>        HStack {<br>            Button(&quot;Privacy Policy&quot;) {<br>               // open privacy policy<br>            }<br><br>            Spacer()<br><br>            Button(&quot;Terms of Use&quot;) {<br>                // open terms of use<br>            }<br>        }<br>        .foregroundStyle(Color(.label))<br>        .padding(.horizontal, 18)<br>        .padding(.top, 2)<br>        .font(.footnote)<br>    }<br>}</pre><p>Let’s now create the simplest implementation of PaywallView</p><pre>struct PaywallView: View {<br><br>    private var buyButton: some View {<br>        Button {<br>            // buy<br>        } label: {<br>            Text(&quot;Continue&quot;)<br>                .padding()<br>                .frame(maxWidth: .infinity)<br>        }<br>        .foregroundStyle(.white)<br>        .font(.title3)<br>        .background(.blue)<br>        .clipShape(.rect(cornerRadius: 12))<br>        .padding(.bottom, 52)<br>        .padding(.horizontal, 18)<br>    }<br><br>    var body: some View {<br>        VStack {<br>            Header()<br>            Spacer() // content will go here<br>            buyButton<br>                .overlay(alignment: .bottom) {<br>                    Footer()<br>                }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MztmLam0nNcI78sc2Y8AfA.png" /></figure><p>We will solve one problem at a time. For now, let’s focus on some logic. Currently, our buttons do nothing. Most likely, you will have a ViewModel to handle these interactions. Let’s create a protocol with the methods we need for now.</p><pre>import Combine<br><br>protocol PaywallViewModel: ObservableObject {<br><br>    func buy()<br>    func close()<br>    func restore()<br>    func openPrivacyPolicy()<br>    func openTermsOfUse()<br>}</pre><p>Let’s add some implementation with no real logic for now, as we are focusing solely on the UI in this article.</p><pre>class ExamplePaywallViewModel: PaywallViewModel {<br><br>    func buy() {<br>        print(&quot;buy&quot;)<br>    }<br><br>    func close() {<br>        print(&quot;close&quot;)<br>    }<br><br>    func restore() {<br>        print(&quot;restore&quot;)<br>    }<br><br>    func openPrivacyPolicy() {<br>        print(&quot;openPrivacyPolicy&quot;)<br>    }<br><br>    func openTermsOfUse() {<br>        print(&quot;openTermsOfUse&quot;)<br>    }<br>}</pre><p>We can now update our components to be generic over our protocol and call the corresponding methods. PaywallView will accept the viewModel in its initializer and pass it to its components, either through the environment or through the initializer. I will use the first approach:</p><pre>struct PaywallView&lt;ViewModel: PaywallViewModel&gt;: View {<br><br>    @ObservedObject private var viewModel: ViewModel<br><br>    init(viewModel: ViewModel) {<br>        self.viewModel = viewModel<br>    }<br><br>    private var headerView: some View {<br>        Header&lt;ViewModel&gt;()<br>            .environmentObject(viewModel)<br>    }<br><br>    private var footerView: some View {<br>        Footer&lt;ViewModel&gt;()<br>            .environmentObject(viewModel)<br>    }<br><br>    private var buyButton: some View {<br>        Button {<br>            viewModel.buy()<br>        } label: {<br>            Text(&quot;Continue&quot;)<br>                .padding()<br>                .frame(maxWidth: .infinity)<br>        }<br>        .foregroundStyle(.white)<br>        .font(.title3)<br>        .background(.blue)<br>        .clipShape(.rect(cornerRadius: 12))<br>        .padding(.bottom, 52)<br>        .padding(.horizontal, 18)<br>    }<br><br>    var body: some View {<br>        VStack {<br>            headerView<br>            Spacer() // content will go here<br>            buyButton<br>                .overlay(alignment: .bottom) {<br>                    footerView<br>                }<br>        }<br>    }<br>}</pre><pre>struct Header&lt;ViewModel: PaywallViewModel&gt;: View {<br><br>    @EnvironmentObject private var viewModel: ViewModel<br><br>    var body: some View {<br>        HStack {<br>            Button {<br>                viewModel.close()<br>            } label: {<br>                Image(systemName: &quot;xmark&quot;)<br>                    .resizable()<br>                    .renderingMode(.template)<br>                    .frame(width: 16, height: 16)<br>            }<br><br>            Spacer()<br><br>            Button(&quot;Restore&quot;) {<br>                viewModel.restore()<br>            }<br>        }<br>        .foregroundStyle(Color(.label))<br>        .padding(.horizontal, 18)<br>        .padding(.top, 2)<br>        .font(.footnote)<br>    }<br>}</pre><pre>struct Footer&lt;ViewModel: PaywallViewModel&gt;: View {<br><br>    @EnvironmentObject private var viewModel: ViewModel<br><br>    var body: some View {<br>        HStack {<br>            Button(&quot;Privacy Policy&quot;) {<br>                viewModel.openPrivacyPolicy()<br>            }<br><br>            Spacer()<br><br>            Button(&quot;Terms of Use&quot;) {<br>                viewModel.openTermsOfUse()<br>            }<br>        }<br>        .foregroundStyle(Color(.label))<br>        .padding(.horizontal, 18)<br>        .padding(.top, 2)<br>        .font(.footnote)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eAc0smtf8jBv0rsqhZizvQ.gif" /></figure><p>Great, we have something working already.</p><p>In a real application, you would likely create a BasePaywallViewModel to encapsulate common logic across all paywalls and then create subclasses to store A/B test-specific logic. Alternatively, you could use any other architectural approach that you find comfortable to work with.</p><p>In the header and footer, we’ve used some hardcoded foreground colors for now, but it’s time to change that. There might be screens where these colors need to be changed due to UI requirements. While we could pass these colors through initializers, there’s a better approach using SwiftUI’s Environment. Let’s create separate environment values for the header and footer to allow for independent color changes.</p><pre>private enum HeaderForegroundColorKey: EnvironmentKey {<br>    static var defaultValue = Color(.label)<br>}<br><br>extension EnvironmentValues {<br><br>    var headerForegroundColor: Color {<br>        get { self[HeaderForegroundColorKey.self] }<br>        set { self[HeaderForegroundColorKey.self] = newValue }<br>    }<br>}<br><br>extension View {<br><br>    func headerForegroundColor(_ color: Color) -&gt; some View {<br>        environment(\.headerForegroundColor, color)<br>    }<br>} <br><br>// Do the same for the Footer</pre><blockquote><strong><em>Note</em></strong><em>: in Xcode 16 the </em><a href="https://developer.apple.com/documentation/swiftui/entry()"><em>Entry</em></a><em> macro can be used to add values to the </em><em>EnvironmentValues</em></blockquote><p>Now we can update the components to use the foreground color passed from the outside:</p><pre>struct Header&lt;ViewModel: PaywallViewModel&gt;: View {<br><br>    @EnvironmentObject private var viewModel: ViewModel<br>    @Environment(\.headerForegroundColor) private var foregroundColor // &lt;-<br><br>    var body: some View {<br>        HStack {<br>            Button {<br>                viewModel.close()<br>            } label: {<br>                Image(systemName: &quot;xmark&quot;)<br>                    .resizable()<br>                    .renderingMode(.template)<br>                    .frame(width: 16, height: 16)<br>            }<br><br>            Spacer()<br><br>            Button(&quot;Restore&quot;) {<br>                viewModel.restore()<br>            }<br>        }<br>        .foregroundStyle(foregroundColor)   // &lt;--------<br>        .padding(.horizontal, 18)<br>        .padding(.top, 2)<br>        .font(.footnote)<br>    }<br>}</pre><pre>PaywallView(viewModel: ExamplePaywallViewModel())<br>    .headerForegroundColor(.red)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9qBDAEVdnMH9CQ1YHYv1Q.png" /></figure><p>You can use the Environment to change the font of the texts, hide buttons, and more. It employs the same technique, so I won’t repeat it here.</p><p>What we have left is the content itself. Let’s update the PaywallView to accept and render this content.</p><pre>struct PaywallView&lt;ViewModel: PaywallViewModel, Content: View&gt;: View {<br><br>    @ObservedObject private var viewModel: ViewModel<br>    private let content: Content  // &lt;-------<br><br>    init(<br>        viewModel: ViewModel,<br>        @ViewBuilder content: () -&gt; Content<br>    ) {<br>        self.viewModel = viewModel<br>        self.content = content()<br>    }<br><br>    private var headerView: some View {<br>        Header&lt;ViewModel&gt;()<br>            .environmentObject(viewModel)<br>    }<br><br>    private var footerView: some View {<br>        Footer&lt;ViewModel&gt;()<br>            .environmentObject(viewModel)<br>    }<br><br>    private var buyButton: some View {<br>        Button {<br>            viewModel.buy()<br>        } label: {<br>            Text(&quot;Continue&quot;)<br>                .padding()<br>                .frame(maxWidth: .infinity)<br>        }<br>        .foregroundStyle(.white)<br>        .font(.title3)<br>        .background(.blue)<br>        .clipShape(.rect(cornerRadius: 12))<br>        .padding(.bottom, 52)<br>        .padding(.horizontal, 18)<br>    }<br><br>    var body: some View {<br>        VStack {<br>            headerView<br>            content                  // &lt;---------<br>            buyButton<br>                .overlay(alignment: .bottom) {<br>                    footerView<br>                }<br>        }<br>    }<br>}</pre><pre>PaywallView(viewModel: ExamplePaywallViewModel()) {<br>    Rectangle()<br>        .fill(.yellow)<br>}<br>.headerForegroundColor(.red)<br>.background(.gray.opacity(0.4))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fc77uXzXob9qx5n-MpvGVA.png" /></figure><p>Of course, your layout will be more meaningful, but I just wanted to illustrate some key points here:</p><ul><li>You can pass any view to the PaywallView, and it will render it, adding the header and footer automatically.</li><li>You can apply a background to the PaywallView, which will cover the entire screen.</li><li>In the example, we used a Rectangle as the content. Since shapes like Rectangle occupy all available space, it stretches to fill the area between the header and footer. However, if we apply fixed frames, our layout may break (see screenshots below).</li><li>We use a VStack in the PaywallView to stack the header, content, and footer vertically. However, there might be cases where you want the content to be positioned beneath the header, for example.</li><li>Additionally, the header, content, and footer are inside the safe area by default. There might be scenarios where you want the content to align with the top of the screen while keeping the header in its original position.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fbo8LzWEEFRghyelRoVWAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_1QYdOXn7EQSolYT6msjw.png" /><figcaption>Rectangle with fixed frames ( .frame(height: …) )</figcaption></figure><p>As consumers of PaywallView, we want to pass the content and configure its layout with the header and footer. However, handling all possible layout variations directly within PaywallView can be overwhelming and error-prone.</p><p>When faced with complex layout requirements, <strong>delegating</strong> responsibility is often the best solution. By shifting the layout responsibility from PaywallView to a dedicated layout manager, we can simplify PaywallView and ensure that the layout is handled correctly based on the information it provides.</p><p>Let’s delegate the layout responsibilities to another component that can manage it effectively.</p><pre>protocol PaywallLayout {<br><br>    associatedtype Body: View<br><br>    @ViewBuilder func layout(<br>        header: AnyView,<br>        content: AnyView,<br>        footer: AnyView,<br>        proxy: GeometryProxy<br>    ) -&gt; Body<br>}</pre><p>Let’s implement the layout we currently have: placing the header, content, and footer one below the other inside the safe area.</p><pre>struct ContentBetweenSafeArea: PaywallLayout {<br><br>    @ViewBuilder func layout(<br>        header: AnyView,<br>        content: AnyView,<br>        footer: AnyView,<br>        proxy: GeometryProxy<br>    ) -&gt; some View {<br>        VStack(spacing: 0) {<br>            header<br>            Rectangle().fill(.clear)<br>                .overlay {<br>                    content<br>                }<br>                .clipped()<br>            footer<br>        }<br>        .padding(.top, proxy.safeAreaInsets.top)<br>        .padding(.bottom, proxy.safeAreaInsets.bottom)<br>    }<br>}<br><br>extension PaywallLayout where Self == ContentBetweenSafeArea {<br><br>    static var contentBetweenSafeArea: ContentBetweenSafeArea {<br>        ContentBetweenSafeArea()<br>    }<br>}</pre><blockquote><strong><em>Note:</em></strong><em> Instead of using just the content directly, I’ve used a </em><em>Rectangle with overlay and clipping. The </em><em>Rectangle with an overlay ensures that it occupies all the space between the header and footer, even if the content is smaller. The clipping ensures that the content does not overlap the header or footer.</em></blockquote><p>Now, we can use the same technique with the environment to pass and utilize the PaywallLayout.</p><pre>import SwiftUI<br><br>private enum PaywallLayoutKey: EnvironmentKey {<br>    static var defaultValue: any PaywallLayout = ContentBetweenSafeArea()<br>}<br><br>extension EnvironmentValues {<br>    var paywallLayout: any PaywallLayout {<br>        get { self[PaywallLayoutKey.self] }<br>        set { self[PaywallLayoutKey.self] = newValue }<br>    }<br>}<br><br>extension View {<br>    func paywallLayout(_ layout: some PaywallLayout) -&gt; some View {<br>        environment(\.paywallLayout, layout)<br>    }<br>}</pre><pre>import SwiftUI<br><br>struct PaywallView&lt;ViewModel: PaywallViewModel, Content: View&gt;: View {<br><br>    @Environment(\.paywallLayout) private var layout   // &lt;---------<br>    @ObservedObject private var viewModel: ViewModel<br>    private let content: Content<br><br>    init(<br>        viewModel: ViewModel,<br>        @ViewBuilder content: () -&gt; Content<br>    ) {<br>        self.viewModel = viewModel<br>        self.content = content()<br>    }<br><br>    private var headerView: some View {<br>        Header&lt;ViewModel&gt;()<br>            .environmentObject(viewModel)<br>    }<br><br>    private var footerView: some View {<br>        Footer&lt;ViewModel&gt;()<br>            .environmentObject(viewModel)<br>    }<br><br>    private var buyButton: some View {<br>        Button {<br>            viewModel.buy()<br>        } label: {<br>            Text(&quot;Continue&quot;)<br>                .padding()<br>                .frame(maxWidth: .infinity)<br>        }<br>        .foregroundStyle(.white)<br>        .font(.title3)<br>        .background(.blue)<br>        .clipShape(.rect(cornerRadius: 12))<br>        .padding(.bottom, 52)<br>        .padding(.horizontal, 18)<br>    }<br><br>    var body: some View {<br>        GeometryReader { proxy in                 // &lt;-----------<br>            AnyView(layout.layout(<br>                header: AnyView(headerView),<br>                content: AnyView(content),<br>                footer: AnyView(buyButton<br>                    .overlay(alignment: .bottom) {<br>                        footerView<br>                    }),<br>                proxy: proxy<br>            ))<br>            .ignoresSafeArea(edges: .vertical)<br>        }<br>    }<br>}</pre><p>We’ve wrapped the result of the layout in AnyView because, otherwise, the compiler can&#39;t infer the view type. Additionally, we’ve wrapped everything in a GeometryReader and instructed it to ignore the safe area. We pass the GeometryProxy to the layout so it can handle rendering everything correctly.</p><blockquote><strong><em>Note:</em></strong><em> In the demo project, everything should compile now. However, when I tried this in the main application, the compiler still produced an error, indicating that it couldn’t infer the view type. I found an interesting workaround using type erasure. Even if you don’t encounter this problem yourself, I think it can be a usefull techinque to read about. Feel free to skip the following paragraphs if you’re not interested in this workaround.</em></blockquote><p>If you’re experiencing this issue or are curious, here’s how type erasure can be used to solve it:</p><p>Firstly, let’s create a new implementation for PaywallLayout that specifies its result type as AnyView. Similar to AnyView, AnyPaywallLayout will accept any PaywallLayout in its initializer but will avoid being generic.</p><pre>import SwiftUI<br><br>struct AnyPaywallLayout: PaywallLayout {<br><br>    private let layout: (AnyView, AnyView, AnyView, GeometryProxy) -&gt; AnyView<br><br>    init&lt;Layout: PaywallLayout&gt;(_ layout: Layout) {<br>        self.layout = { header, content, footer, proxy in<br>            AnyView(layout.layout(<br>                header: header,<br>                content: content,<br>                footer: footer,<br>                proxy: proxy<br>            ))<br>        }<br>    }<br><br>    @ViewBuilder func layout(<br>        header: AnyView,<br>        content: AnyView,<br>        footer: AnyView,<br>        proxy: GeometryProxy<br>    ) -&gt; AnyView {<br>        layout(header, content, footer, proxy)<br>    }<br>}</pre><p>Now, we will modify our PaywallLayoutKey and everything related to it:</p><pre>import SwiftUI<br><br>private enum PaywallLayoutKey: EnvironmentKey {<br>    static var defaultValue = AnyPaywallLayout(ContentBetweenSafeArea())<br>}<br><br>extension EnvironmentValues {<br>    var paywallLayout: AnyPaywallLayout {<br>        get { self[PaywallLayoutKey.self] }<br>        set { self[PaywallLayoutKey.self] = newValue }<br>    }<br>}<br><br>extension View {<br>    func paywallLayout(_ layout: some PaywallLayout) -&gt; some View {<br>        environment(\.paywallLayout, AnyPaywallLayout(layout))<br>    }<br>}</pre><p>With these changes, the consumers of our API won’t notice any differences, but now the compiler should correctly interpret that the result of the layout is AnyView.</p><p>If we run the app now, there won’t be any visible changes, so you might wonder about the benefit. The real advantage of this approach is its flexibility. It allows us to add additional layouts as needed without having to address everything all at once. This makes it easier to manage and debug specific issues as they arise.</p><p>To demonstrate this, let’s add a new layout that aligns the content to the top edge of the screen. This way, you can see how the system can adapt to different layout requirements while keeping the core functionality intact.</p><pre>import SwiftUI<br><br>struct ContentIgnoringTopEdge: PaywallLayout {<br><br>    @ViewBuilder func layout(<br>        header: AnyView,<br>        content: AnyView,<br>        footer: AnyView,<br>        proxy: GeometryProxy<br>    ) -&gt; some View {<br>        VStack(spacing: 0) {<br>            Rectangle()<br>                .fill(.clear)<br>                .overlay { content }<br>                .clipped()<br>                .overlay(alignment: .top) {<br>                    header.padding(.top, proxy.safeAreaInsets.top)<br>                }<br><br>            footer<br>        }<br>        .padding(.bottom, proxy.safeAreaInsets.bottom)<br>    }<br>}<br><br>extension PaywallLayout where Self == ContentIgnoringTopEdge {<br><br>    static var ignoringTopEdge: ContentIgnoringTopEdge {<br>        ContentIgnoringTopEdge()<br>    }<br>}</pre><p>We can use it like this:</p><pre>PaywallView(viewModel: ExamplePaywallViewModel()) {<br>    Rectangle()<br>        .fill(.yellow)<br>        .frame(height: 1000)<br>}<br>.paywallLayout(.ignoringTopEdge)<br>.headerForegroundColor(.red)<br>.background(.gray.opacity(0.4))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNUFxv4NHcdOqJXAcjA_EQ.png" /></figure><p>The ‘delegation’ approach isn’t new. It’s similar to how SwiftUI’s ViewModifier, ButtonStyle, and other protocols operate.</p><p>Here are some additional ideas to consider:</p><ul><li><strong>Create more layout implementations:</strong> For example, you could add layouts that handle cases where content is beneath the footer.</li><li><strong>Pass arguments to layouts:</strong> Allow for configuration of the layout by passing arguments. For instance, you could pass the alignment of the overlay for the content Rectangle to control how the content is displayed if it&#39;s too small. You might also pass arguments to determine if the content should be clipped when it’s too large.</li><li><strong>Pass the header and footer as arguments:</strong> Similar to how you pass the content, you could pass the header and footer as arguments to PaywallView. Provide an API that makes passing these arguments optional to simplify the usage for cases where defaults are acceptable:</li></ul><pre>struct PaywallView&lt;ViewModel: PaywallViewModel, Content: View, HeaderView: View, FooterView: View&gt;: View {<br><br>    ...<br>    private let content: Content<br>    private let header: HeaderView<br>    private let footer: FooterView<br><br>    init(<br>        viewModel: ViewModel,<br>        @ViewBuilder content: () -&gt; Content,<br>        @ViewBuilder header: () -&gt; HeaderView,<br>        @ViewBuilder footer: () -&gt; FooterView<br>    ) {<br>        self.viewModel = viewModel<br>        self.content = content()<br>        self.header = header()<br>        self.footer = footer()<br>    }<br><br>    private var headerView: some View {<br>        header<br>            .environmentObject(viewModel)<br>    }<br><br>    private var footerView: some View {<br>        footer<br>            .environmentObject(viewModel)<br>    }<br>...<br>}<br><br>extension PaywallView where HeaderView == Header&lt;ViewModel&gt;, FooterView == Footer&lt;ViewModel&gt; {<br><br>    init(<br>        viewModel: ViewModel,<br>        @ViewBuilder content: () -&gt; Content<br>    ) {<br>        self.init(<br>            viewModel: viewModel,<br>            content: content<br>        ) {<br>            Header&lt;ViewModel&gt;()<br>        } footer: {<br>            Footer&lt;ViewModel&gt;()<br>        }<br>    }<br>}</pre><p><strong>In summary,</strong> this approach allows you to focus on implementing only the new elements for your A/B test, which can save you a significant amount of time. At the same time, you retain the flexibility to configure the PaywallView as needed, ensuring that you can adapt to various requirements and scenarios efficiently.</p><p>Don’t hesitate to ask questions in the comments or share your thoughts. <br>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8242106dada" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Pitfalls: My Failures and Lessons Learned]]></title>
            <link>https://medium.com/@gloomikon/swiftui-pitfalls-my-failures-and-lessons-learned-558b7e35e6e0?source=rss-d3bcf152f392------2</link>
            <guid isPermaLink="false">https://medium.com/p/558b7e35e6e0</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[tooltips]]></category>
            <dc:creator><![CDATA[gloomikon]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 18:44:13 GMT</pubDate>
            <atom:updated>2024-07-06T18:44:13.815Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1</h4><p>Implementing more features with SwiftUI has presented me with various challenges. <br>Some were easy to overcome, while others took more time and effort, possibly due to my lack of knowledge or experience.</p><p>To help you complete similar tasks more efficiently, I decided to share my explorations and propose possible solutions.</p><p>I’ll split the article into several parts so that the amount of information is not overwhelming. In each part, I’ll explain the work that needed to be done, my initial attempts, the problems I encountered, my discoveries, and the final results</p><p>Without further ado, I invite you to part one</p><h3>Case name: Tooltip</h3><p>My task was to implement helpers-tooltips in the chat screen, which were shown when the user tapped a corresponding button. When the user taps the email tooltip — the mail app should open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-m9KMciaYqBo6-u18bKgg.gif" /></figure><p>Let’s implement this tooltip step-by-step!</p><blockquote><strong>Note:</strong> In the code below I’ll be using a simplified shape for tooltip. The shape for tooltip can be found <a href="https://github.com/KOMA-Inc/SwiftUIPlus/blob/main/Sources/SwiftUIPlus/Shapes/TooltipShape.swift">here</a></blockquote><p>We’ll start with a skeleton for our future screen</p><pre>struct ExampleView: View {<br><br>    var helpButton: some View {<br>        Button {<br>            print(&quot;Info&quot;)<br>        } label: {<br>            Image(systemName: &quot;questionmark.circle&quot;)<br>                .resizable()<br>                .frame(width: 18, height: 18)<br>                .foregroundStyle(.white)<br>        }<br>    }<br><br>    private var header: some View {<br>        helpButton<br>            .padding(.leading, 70)<br>            .frame(maxWidth: .infinity, alignment: .leading)<br>            .padding()<br>            .background(Color.orange)<br>    }<br><br>    var body: some View {<br>        VStack(spacing: 0) {<br>            header<br>            Rectangle().fill(.gray)<br>        }<br>        .ignoresSafeArea(edges: .bottom)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Heh6YAD9zPcSKmNIQHgJaQ.png" /></figure><p>Let’s also create a separate view for our tooltip:</p><pre>struct Tooltip: View {<br>    var body: some View {<br>        VStack(alignment: .leading, spacing: 4) {<br>            Text(&quot;If you need help, please contact&quot;)<br>                .foregroundStyle(.white)<br>            Text(&quot;gloomikon@gmail.com&quot;)<br>                .foregroundStyle(.blue)<br>        }<br>        .font(.headline)<br>        .padding()<br>        .background(.black)<br>        .clipShape(.rect(cornerRadius: 6))<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*zE7Dqa4H58QCVSyI8BGFRw.png" /></figure><p>Now we need to understand how to display the tooltip under the help button. With SwiftUI, there are often multiple solutions for a single problem, so we’ll look at one of them. We are going to use an overlay to display the tooltip.</p><pre>private var header: some View {<br>    helpButton<br>        .overlay {<br>            Tooltip()<br>        }<br>        ....<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ae_phVGqi5wFAE5XR-OvrA.png" /></figure><p>However, an overlay adopts the size of the view it is applied to. This means that despite the tooltip being quite large, it will be clipped to the size of the button, which is 18x18.</p><p>To fix this, we can tell our tooltip to ignore the proposed size by using the fixedSize() modifier:</p><pre>private var header: some View {<br>    helpButton<br>        .overlay {<br>            Tooltip()<br>                .fixedSize()<br>        }<br>        ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqKCLdsHfPpatO2bbfCd6w.png" /></figure><p>Good news: the tooltip is no longer clipped. Bad news: it’s displayed in the wrong position.</p><p>What is happening is that the overlay, by default, centers its content with the view it is applied to. This means the center of the button and the center of the tooltip are aligned. However, we want to achieve a different layout:</p><ul><li>The top of the tooltip should be aligned with the bottom of the button, plus some extra padding.</li><li>The center of the button should be at 1/4 of the tooltip’s width.</li></ul><p>This may seem complicated, but it’s actually quite simple. We will use a different alignment for the overlay and “override” some alignments for the tooltip using the alignmentGuide modifier.</p><pre>private var header: some View {<br>    helpButton<br>        .overlay(alignment: .bottom) {<br>            Tooltip()<br>                .fixedSize()<br>                .alignmentGuide(.bottom) { $0[.top] - 8 }<br>                .alignmentGuide(HorizontalAlignment.center) { $0.width / 4 }<br>        }<br>        ...<br>}</pre><p>I’ve used different syntaxes here for illustration purposes; however, you can use whichever you find more comfortable.</p><p>We implemented exactly what we discussed. We specified that the tooltip’s bottom (short for VerticalAlignment.bottom) is actually its top (short for VerticalAlignment.top) with some padding. We also indicated that its horizontal center (HorizontalAlignment.center, which cannot be written as just .center because the compiler would confuse it with VerticalAlignment.center) is actually located at one-fourth of its width.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oi92gBTDFc_rzUun9z2gqg.png" /></figure><p>We are almost there! The tooltip is positioned correctly, but it’s covered by a gray rectangle. This occurs because the tooltip overlaps with the rectangle, which is defined later in the VStack. Therefore, the rectangle has a higher stacking order priority. We can resolve this by setting a zIndex for our header:</p><pre>private var header: some View {<br>    helpButton<br>        .overlay(alignment: .bottom) {<br>            Tooltip()<br>                .fixedSize()<br>                .alignmentGuide(.bottom) { $0[.top] - 8 }<br>                .alignmentGuide(HorizontalAlignment.center) { $0.width / 4 }<br>        }<br>        .zIndex(1)<br>        ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywrA22kzZHsCiXK0fag1Ww.png" /></figure><p>Great! Now the tooltip is correctly positioned. However, it’s displayed constantly. Let’s change the logic to show/hide it based on the button tap. We’ll ignore the animation for now and add it later. The steps are straightforward:</p><ol><li>Add a state flag property.</li><li>Toggle the flag on the button tap.</li><li>Use this flag in the overlay to display the tooltip only if the flag is true.</li></ol><pre>// 1<br>@State private var showTooltip = false<br><br>var helpButton: some View {<br>    Button {<br>        // 2<br>        showTooltip.toggle()<br>    } label: {<br>        Image(systemName: &quot;questionmark.circle&quot;)<br>            .resizable()<br>            .frame(width: 18, height: 18)<br>            .foregroundStyle(.white)<br>    }<br>}<br><br>private var header: some View {<br>    helpButton<br>        .overlay(alignment: .bottom) {<br>            // 3<br>            if showTooltip {<br>                Tooltip()<br>                    .fixedSize()<br>                    .alignmentGuide(.bottom) { $0[.top] - 8 }<br>                    .alignmentGuide(HorizontalAlignment.center) { $0.width / 4 }<br>            }<br>        }<br>        .zIndex(1)<br>        ...<br>}</pre><p>And… we broke everything!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*L1Qna2mDb8lYNt-j2A_7zQ.gif" /></figure><p>It took me some time to understand what was happening here. After some investigation, I realized that comparing the types of content before and after adding the state property gave different results:</p><pre>@ViewBuilder<br>private var tooltip: some View {<br>    Tooltip()<br>        .fixedSize()<br>        .alignmentGuide(.bottom) { $0[.top] - 8 }<br>        .alignmentGuide(HorizontalAlignment.center) { $0.width / 4 }<br>}<br><br>print(type(of: tooltip)) // ModifiedContent&lt;ModifiedContent&lt;ModifiedContent&lt;Tooltip, _FixedSizeLayout&gt;, _AlignmentWritingModifier&gt;, _AlignmentWritingModifier&gt;<br><br>@ViewBuilder<br>private var tooltip: some View {<br>    if showTooltip {<br>        Tooltip()<br>            .fixedSize()<br>            .alignmentGuide(.bottom) { $0[.top] - 8 }<br>            .alignmentGuide(HorizontalAlignment.center) { $0.width / 4 }<br>    }<br>}<br><br>print(type(of: tooltip)) // Optional&lt;ModifiedContent&lt;ModifiedContent&lt;ModifiedContent&lt;Tooltip, _FixedSizeLayout&gt;, _AlignmentWritingModifier&gt;, _AlignmentWritingModifier&gt;&gt;</pre><p>This is understandable, as we get into this case of ViewBuilder :</p><pre>/// Produces an optional view for conditional statements in multi-statement<br>/// closures that&#39;s only visible when the condition evaluates to true.<br>public static func buildIf&lt;Content&gt;(_ content: Content?) -&gt; Content? where Content : View</pre><p>The way I see it, using alignmentGuide with optional content doesn’t work, so we need to find another approach. There are various solutions for this issue, so I’ll share the one I’ve come up with. Since we want to scale the tooltip with animation upon button tap, let’s use the scaleEffect modifier and incorporate some animation right away:</p><pre>private var header: some View {<br>    helpButton<br>        .overlay(alignment: .bottom) {<br>            Tooltip()<br>                .fixedSize()<br>                .alignmentGuide(.bottom) { $0[.top] - 8 }<br>                .alignmentGuide(HorizontalAlignment.center) { $0.width / 4 }<br>                .scaleEffect(<br>                    showTooltip ? CGSize(width: 1.0, height: 1.0) : .zero,<br>                    anchor: UnitPoint(x: 0.25, y: 0)<br>                )<br>                .animation(.easeInOut(duration: 0.3), value: showTooltip)<br>        }<br>        .zIndex(1)<br>        ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*4T3ZvuYQJ_AsVdhnJ0ypNw.gif" /></figure><p>Finally! We’ve made a lot of progress, and now it works. Or does it?</p><p>Well, I initially thought so. Then, I received a bug report from QA.</p><p>To understand the bug, let’s add a new feature to our screen: let’s change the navigation bar background color to a random one each time the user taps a gray rectangle. Sounds easy enough:</p><pre>@State private var background: Color = .orange<br><br>private var header: some View {<br>    helpButton<br>        ...<br>        .background(background)<br>}<br><br>...<br><br>Rectangle().fill(.gray)<br>    .onTapGesture {<br>        background = .random<br>    }<br><br>private extension Color {<br>    static var random: Color {<br>        Color(<br>            red: .random(in: 0...1),<br>            green: .random(in: 0...1),<br>            blue: .random(in: 0...1)<br>        )<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*ZlfikAvJmqL4b8o8555UsA.gif" /></figure><p>It seems to work, however, when I tap into the area where the tooltip should appear — nothing happens.</p><p>As an original bug was more complicated than that, it again took me some time to realize what was happening.</p><p>The issue lies with the scaleEffect modifier we used earlier—it&#39;s just an effect and doesn&#39;t change the original frame of the content. This means the tooltip is still there, but we just don&#39;t see it.</p><p>A possible solution is to disable user interaction for the tooltip when it is hidden:</p><pre>.overlay(alignment: .bottom) {<br>    Tooltip()<br>        ...<br>        .allowsHitTesting(showTooltip)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*ipZ6871JunRY6_tlS0xuQg.gif" /></figure><p>Now everything works perfectly ✨</p><p>This concludes the first part. I hope you’ve found something useful for yourself.</p><p>If you want to try everything out, you can find the final code <a href="https://gist.github.com/gloomikon/bf0060394eef6be6f3da933ac9ef5455">here</a>. Feel free to add more buttons and overlays to display other tooltips. You can also control the state properties with timers to make the tooltips auto-dismissable after some time.</p><p>If you have alternative solutions for the mentioned problems, share them in the comments.</p><p>Thanks and good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=558b7e35e6e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Animated Canvas]]></title>
            <link>https://medium.com/@gloomikon/swiftui-animated-canvas-2bca890ca914?source=rss-d3bcf152f392------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bca890ca914</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[timelimeview]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[canvas]]></category>
            <dc:creator><![CDATA[gloomikon]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 15:15:05 GMT</pubDate>
            <atom:updated>2024-06-29T15:15:05.104Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Let’s become better together</blockquote><p>After being inspired by numerous articles, blog posts, and videos, I decided to implement a generic system for animated canvases. This final implementation enables the creation of various animations using the same system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*vz9Z5zcUyOU5MLf9p3UGKQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Bq1iGdvIzkTyRUuA7KFDnA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*j7dED0v_5PpVuAGzBSw3aQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*KT_dU6t6K9jB1Myu2Q0Ieg.gif" /></figure><blockquote><strong>Note: </strong>All the examples can be found in the <a href="https://github.com/KOMA-Inc/Galaxy">GitHub repository</a>.</blockquote><p>Let’s start with a simple example and explore how to create a reusable generic system. Without further ado, let’s build the animation shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*6rvyaEf40LP1sRJFFvYxow.gif" /></figure><p>Two main components of our animation view are the <a href="https://developer.apple.com/documentation/swiftui/timelineview">TimelineView</a> and the <a href="https://developer.apple.com/documentation/swiftui/canvas">Canvas</a>. The TimelineView redraws its content at scheduled points in time, while the Canvas is used to draw 2D graphics within a SwiftUI view using <a href="https://developer.apple.com/documentation/swiftui/graphicscontext">GraphicsContext</a> and <a href="https://developer.apple.com/documentation/corefoundation/cgsize">CGSize</a>.</p><p>Additionally, the Canvas accepts a symbolsparameter. Simply put, you can tag views uniquely with the <em>.tag(&lt;some_tag&gt;)</em> modifier and later retrieve them from the context using context.resolveSymbol(id: &lt;some_tag&gt;).</p><pre>struct AnimatedView: View {<br><br>    var body: some View {<br>        TimelineView(.animation) { timeline in<br>            Canvas { context, size in<br>                // drawing<br>            } symbols: {<br>                // symbols<br>            }<br>        }<br>    }<br>}</pre><p>Next, we want to introduce a data model that represents the pieces of drawing in the Canvas. In our example, this will be an Emoji. We can decide what data we need for the Emoji, so for simplicity, let’s proceed with a minimal version:</p><pre>struct Emoji {<br><br>    /// Current position in canvas<br>    var position: CGPoint<br><br>    /// Emoji character that will be displayed<br>    let character: Character<br><br>    /// The speed at which the position will change<br>    let speed: CGFloat<br>}</pre><p>The algorithm for drawing is as follows:</p><ol><li>Create an array of Emojis and store it inside the View.</li><li>Redraw each Emoji in each frame.</li><li>Update the position of each Emoji in each frame.</li></ol><p>Let’s update the code to perform these steps.</p><p><strong>Step 1 :</strong></p><pre>struct AnimatedView: View {<br><br>    @State private var emojis: [Emoji] = []<br><br>    var body: some View {<br>        TimelineView(.animation) { timeline in<br>            Canvas { context, size in<br>                // drawing<br>            } symbols: {<br>                // symbols<br>            }<br>        }<br>        .onAppear {<br>            emojis = (1...100).map { _ in<br>                Emoji(<br>                    position: &lt;CGPoint&gt;,<br>                    character: [&quot;🦦&quot;, &quot;😍&quot;, &quot;👾&quot;, &quot;👻&quot;].randomElement()!,<br>                    speed: .random(in: 2...4)<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>We’ll add a @State private property and create 100 emojis when the view appears. However, we need to specify the position of each emoji. We have two options here:</p><ol><li>Make the position in a range of [0, 1] and later multiply it by the size of the Canvas.</li><li>Wrap the TimelineView inside a <a href="https://developer.apple.com/documentation/swiftui/geometryreader">GeometryReader</a> and use the size directly.</li></ol><p>Since both TimelineView and GeometryReader will occupy all the available space, there is no issue with using GeometryReader. Thus, we will proceed with the second approach.</p><ul><li>Make the position in a range of [0; 1] and later multiply it by the size of the Canvas;</li><li>Wrap the TimelineView inside a <a href="https://developer.apple.com/documentation/swiftui/geometryreader">GeometryReader</a> and use the size at once.</li></ul><p>As both TimelineView and GeometryReader will occupy all the space that was proposed, there is no problem with using GeometryReader, thus we will proceed with the second approach.</p><pre>struct AnimatedView: View {<br><br>    @State private var emojis: [Emoji] = []<br><br>    var body: some View {<br>        GeometryReader { proxy in<br>            TimelineView(.animation) { timeline in<br>                Canvas { context, size in<br>                    // drawing<br>                } symbols: {<br>                    // symbols<br>                }<br>            }<br>            .onAppear {<br>                emojis = (1...100).map { _ in<br>                    Emoji(<br>                        position: CGPoint(<br>                            x: .random(in: 0...proxy.size.width),<br>                            y: .random(in: 0...proxy.size.height)<br>                        ),<br>                        character: [&quot;🦦&quot;, &quot;😍&quot;, &quot;👾&quot;, &quot;👻&quot;].randomElement()!,<br>                        speed: .random(in: 2...4)<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}<br></pre><p><strong>Step 2 :</strong></p><p>Let’s update now the position of Emojis using their speed.</p><pre>struct AnimatedView: View {<br><br>    @State private var emojis: [Emoji] = []<br><br>    var body: some View {<br>        GeometryReader { proxy in<br>            TimelineView(.animation) { timeline in<br>                Canvas { context, size in<br>                    DispatchQueue.main.async {<br>                        self.update(size: size)<br>                    }<br>                } symbols: {<br>                    // symbols<br>                }<br>            }<br>            .onAppear {<br>                ...<br>            }<br>        }<br>    }<br><br>    private func update(size: CGSize) {<br>        emojis.indices.forEach { idx in<br>            emojis[idx].position.y += emojis[idx].speed<br>            if emojis[idx].position.y &gt; size.height {<br>                emojis[idx].position.y = .zero<br>            }<br>        }<br>    }<br>}</pre><blockquote><strong>Note: </strong>We need to call <strong>update </strong>in the <strong>DispatchQueue.main.async, </strong>as otherwise we are updating the State during view updates, which will result in a wrong behaviour.</blockquote><p><strong>Step 3:</strong></p><p>Finally, let’s display everything on the screen. We are going to draw a SwiftUI View in the context, so as mentioned before, firstly we need to “register” all possible views in the Canvas:</p><pre>...<br>Canvas { context, size in<br>    ...<br>} symbols: {<br>    ForEach([&quot;🦦&quot;, &quot;😍&quot;, &quot;👾&quot;, &quot;👻&quot;] as [Character], id: \.self) { char in<br>        Text(String(char))<br>            .id(char)<br>    }<br>}</pre><p>And here is how we use these Views afterward:</p><pre>struct AnimatedView: View {<br><br>    @State private var emojis: [Emoji] = []<br><br>    var body: some View {<br>        GeometryReader { proxy in<br>            TimelineView(.animation) { timeline in<br>                Canvas { context, size in<br>                    self.draw(in: context)<br>                    DispatchQueue.main.async {<br>                        self.update(size: size)<br>                    }<br>                } symbols: {<br>                    ForEach([&quot;🦦&quot;, &quot;😍&quot;, &quot;👾&quot;, &quot;👻&quot;] as [Character], id: \.self) { char in<br>                        Text(String(char))<br>                            .id(char)<br>                    }<br>                }<br>            }<br>            .onAppear {<br>                ...<br>            }<br>        }<br>    }<br><br>    private func draw(in context: GraphicsContext) {<br>        for emoji in emojis {<br>            guard let view = context.resolveSymbol(id: emoji.character) else { <br>                continue <br>            }<br><br>            context.draw(<br>                view,<br>                in: CGRect(<br>                    origin: emoji.position,<br>                    size: CGSize(width: 10, height: 10)<br>                )<br>            )<br>        }<br>    }<br>    ...<br>}</pre><p>At this point, we’ve implemented the Emojis shower animation. But we still have an even more interesting task - how we can make it simple for reuse and extension? What if we want to have some other logic of position updating or draw something completely different?</p><p>Well actually, it is not so hard. As you remember, our sequence of actions is really simple and straightforward: create, update, draw. So what are those things that are tightly coupled with our current concrete implementation?</p><ul><li>Number of elements</li><li>The element itself</li><li>The logic of the element’s creation</li><li>The logic of the element’s update</li><li>The logic of the element’s drawing</li></ul><p>Our task is to “turn around” the responsibilities.</p><p><strong>Firstly</strong>, let’s make the element a protocol so that it can be anything and move the creation, updating, and drawing to its responsibilities.</p><p><strong>Secondly</strong>, let’s make the system generic over this element and make it accept the number of elements to display and a function to create an element.</p><p><strong>Lastly</strong>, let’s make our system provide the element with all the data it has. This can be handy for future users of our API.</p><p>Let’s start with the creation part. For now, let’s add some empty protocol for our element that we will fill later. All we want to do for creation step is to use some kind of element builder instead of calling</p><pre>emojis = (1...100).map { _ in <br>    Emoji(...)<br>}</pre><p>At this point of time, we have an index of the element, that we were ignoring previously, and the size of the canvas. Let’s extract these pieces of data into a structure that can be used in the element’s builder:</p><pre>public protocol GalaxyElement {<br>    // TODO<br>}<br><br>public struct GalaxyElementCreationInput {<br>    public let id: Int<br>    public let spaceSize: CGSize<br>}<br><br>public struct GalaxyView&lt;Element: GalaxyElement&gt;: View {<br><br>    @State private var elements: [Element] = []<br><br>    private let count: Int<br>    private let elementBuilder: (GalaxyElementCreationInput) -&gt; Element<br><br>    public init(<br>        count: Int,<br>        elementBuilder: @escaping (GalaxyElementCreationInput) -&gt; Element<br>    ) {<br>        self.count = count<br>        self.elementBuilder = elementBuilder<br>    }<br><br>    public var body: some View {<br>        GeometryReader { proxy in<br>            TimelineView(.animation) { timeline in<br>                Canvas { context, size in<br>                    ...<br>                } symbols: {<br>                    // TODO<br>                }<br>            }<br>            .onAppear {<br>                create(size: proxy.size)<br>            }<br>        }<br>    }<br><br>    private func create(size: CGSize) {<br>        elements = (0..&lt;count).map {<br>            elementBuilder(GalaxyElementCreationInput(id: $0, spaceSize: size))<br>        }<br>    }<br>}</pre><p>Symbols property is another thing that can be passed outside. Let’s update our GalaxyView a bit:</p><pre>public struct GalaxyView&lt;Symbols: View, Element: GalaxyElement&gt;: View {<br><br>    ...<br>    private let symbols: Symbols<br><br><br>    public init(<br>        count: Int,<br>        elementBuilder: @escaping (GalaxyElementCreationInput) -&gt; Element,<br>        @ViewBuilder symbols: () -&gt; Symbols<br>    ) {<br>        self.count = count<br>        self.elementBuilder = elementBuilder<br>        self.symbols = symbols()<br>    }<br><br>    var body: some View {<br>        ...<br>        Canvas(...) { <br>           ...<br>        } symbols: {<br>            symbols<br>        }<br>    }<br>}</pre><p>We can also add an initializer for the cases when there is no need for symbols property:</p><pre>public extension GalaxyView where Symbols == EmptyView {<br>    init(<br>        count: Int,<br>        elementBuilder: @escaping (GalaxyElementCreationInput) -&gt; Element<br>    ) {<br>        self.init(count: count, elementBuilder: elementBuilder, symbols: { EmptyView() } )<br>    }<br>}</pre><p>For updating the element, the system can provide it with the size of the canvas. However, we are also can make the use of timeline property of the TimelineView and calculate the time between the frames as well as the total elapsed time.</p><pre>public protocol GalaxyElement {<br><br>    mutating func travel(<br>        in space: CGSize,<br>        timeElapsed: TimeInterval,<br>        frameTimeDelta: TimeInterval<br>    )<br>}<br><br>...<br><br>public struct GalaxyView&lt;Symbols: View, Element: GalaxyElement&gt;: View {<br><br>    @State private var start = Date.now<br>    @State private var lastUpdate = Date.now<br><br>    ...<br><br>    public var body: some View {<br>        GeometryReader { proxy in<br>            TimelineView(.animation) { timeline in<br>                Canvas { context, size in<br>                    DispatchQueue.main.async {<br>                        update(<br>                            time: start.distance(to: timeline.date),<br>                            timeDelta: lastUpdate.distance(to: timeline.date),<br>                            size: size<br>                        )<br><br>                        lastUpdate = timeline.date<br>                    }<br>                } symbols: {<br>                    symbols<br>                }<br>            }<br>            .onAppear {<br>                create(size: proxy.size)<br>            }<br>        }<br>    }<br><br>    private func update(time: TimeInterval, timeDelta: TimeInterval, size: CGSize) {<br>        elements.indices.forEach { idx in<br>            elements[idx].travel(in: size, timeElapsed: time, frameTimeDelta: timeDelta)<br>        }<br>    }<br>}</pre><p>The drawing step is pretty similar with the only difference being that the element also needs a context to draw itself into.</p><pre><br>public protocol GalaxyElement {<br><br>    ...<br><br>    func draw(<br>        in space: CGSize,<br>        timeElapsed: TimeInterval,<br>        frameTimeDelta: TimeInterval,<br>        using context: GraphicsContext<br>    )<br>}<br><br>...<br><br>public struct GalaxyView&lt;Symbols: View, Element: GalaxyElement&gt;: View {<br><br>    @State private var start = Date.now<br>    @State private var lastUpdate = Date.now<br><br>    ...<br><br>    public var body: some View {<br>        GeometryReader { proxy in<br>            TimelineView(.animation) { timeline in<br>                Canvas { context, size in<br>                    draw(<br>                        time: start.distance(to: timeline.date),<br>                        timeDelta: lastUpdate.distance(to: timeline.date),<br>                        size: size,<br>                        context: context<br>                    )<br><br>                    ...<br>                } symbols: {<br>                    symbols<br>                }<br>            }<br>            .onAppear {<br>                create(size: proxy.size)<br>            }<br>        }<br>    }<br><br>    private func draw(<br>        time: TimeInterval,<br>        timeDelta: TimeInterval,<br>        size: CGSize,<br>        context: GraphicsContext<br>    ) {<br>        elements.forEach { element in<br>            element.draw(in: size, timeElapsed: time, frameTimeDelta: timeDelta, using: context)<br>        }<br>    }<br><br>    ...<br>}</pre><p>The final code for our core of the galaxy system looks like this:</p><pre>import SwiftUI<br><br>public protocol GalaxyElement {<br><br>    mutating func travel(<br>        in space: CGSize,<br>        timeElapsed: TimeInterval,<br>        frameTimeDelta: TimeInterval<br>    )<br><br>    func draw(<br>        in space: CGSize,<br>        timeElapsed: TimeInterval,<br>        frameTimeDelta: TimeInterval,<br>        using context: GraphicsContext<br>    )<br>}<br><br>public struct GalaxyElementCreationInput {<br>    public let id: Int<br>    public let spaceSize: CGSize<br>}<br><br>public struct GalaxyView&lt;Symbols: View, Element: GalaxyElement&gt;: View {<br><br>    @State private var start = Date.now<br>    @State private var lastUpdate = Date.now<br>    @State private var elements: [Element] = []<br><br>    private let count: Int<br>    private let elementBuilder: (GalaxyElementCreationInput) -&gt; Element<br>    private let symbols: Symbols<br><br>    public init(<br>        count: Int,<br>        elementBuilder: @escaping (GalaxyElementCreationInput) -&gt; Element,<br>        @ViewBuilder symbols: () -&gt; Symbols<br>    ) {<br>        self.count = count<br>        self.elementBuilder = elementBuilder<br>        self.symbols = symbols()<br>    }<br><br>    public var body: some View {<br>        GeometryReader { proxy in<br>            TimelineView(.animation) { timeline in<br>                Canvas { context, size in<br><br>                    draw(<br>                        time: start.distance(to: timeline.date),<br>                        timeDelta: lastUpdate.distance(to: timeline.date),<br>                        size: size,<br>                        context: context<br>                    )<br><br>                    DispatchQueue.main.async {<br><br>                        update(<br>                            time: start.distance(to: timeline.date),<br>                            timeDelta: lastUpdate.distance(to: timeline.date),<br>                            size: size<br>                        )<br><br>                        lastUpdate = timeline.date<br>                    }<br>                } symbols: {<br>                    symbols<br>                }<br>            }<br>            .onAppear {<br>                create(size: proxy.size)<br>            }<br>        }<br>    }<br><br>    private func draw(<br>        time: TimeInterval,<br>        timeDelta: TimeInterval,<br>        size: CGSize,<br>        context: GraphicsContext<br>    ) {<br>        elements.forEach { element in<br>            element.draw(in: size, timeElapsed: time, frameTimeDelta: timeDelta, using: context)<br>        }<br>    }<br><br>    private func update(time: TimeInterval, timeDelta: TimeInterval, size: CGSize) {<br>        elements.indices.forEach { idx in<br>            elements[idx].travel(in: size, timeElapsed: time, frameTimeDelta: timeDelta)<br>        }<br>    }<br><br>    private func create(size: CGSize) {<br>        elements = (0..&lt;count).map {<br>            elementBuilder(GalaxyElementCreationInput(id: $0, spaceSize: size))<br>        }<br>    }<br>}<br><br>public extension GalaxyView where Symbols == EmptyView {<br>    init(<br>        count: Int,<br>        elementBuilder: @escaping (GalaxyElementCreationInput) -&gt; Element<br>    ) {<br>        self.init(count: count, elementBuilder: elementBuilder, symbols: { EmptyView() } )<br>    }<br>}</pre><p>Using the Galaxy system, we can now rewrite our Emojis shower animation:</p><pre>private struct Emoji: GalaxyElement {<br><br>    private var position: CGPoint<br>    private let character: Character<br>    private let speed: CGFloat<br><br>    mutating func travel(<br>        in space: CGSize,<br>        timeElapsed _: TimeInterval,<br>        frameTimeDelta _: TimeInterval<br>    ) {<br>        position.y += speed<br>        if position.y &gt; space.height {<br>            position.y = .zero<br>        }<br>    }<br><br>    func draw(<br>        in space: CGSize,<br>        timeElapsed: TimeInterval,<br>        frameTimeDelta: TimeInterval,<br>        using context: GraphicsContext<br>    ) {<br>        guard let view = context.resolveSymbol(id: character) else {<br>            return<br>        }<br><br>        context.draw(<br>            view,<br>            in: CGRect(<br>                origin: position,<br>                size: CGSize(width: 10, height: 10)<br>            )<br>        )<br>    }<br><br>    static let characters: [Character] = [&quot;🦦&quot;, &quot;😍&quot;, &quot;👾&quot;, &quot;👻&quot;]<br><br>    static func create(in size: CGSize) -&gt; Self {<br>        Self(<br>            position: CGPoint(<br>                x: .random(in: 0...size.width),<br>                y: .random(in: 0...size.height)<br>            ),<br>            character: Self.characters.randomElement()!,<br>            speed: .random(in: 2...4)<br>        )<br>    }<br>}<br><br>struct AnimatedView: View {<br><br>    var body: some View {<br>        GalaxyView(<br>            count: 100) { input in<br>                Emoji.create(in: input.spaceSize)<br>            } symbols: {<br>                ForEach(Emoji.characters, id: \.self) { char in<br>                    Text(String(char))<br>                        .id(char)<br>                }<br>            }<br><br>    }<br>}</pre><p>By implementing different GalaxyElements, you can create astonishing animations using native techniques. More examples you can explore in the <a href="https://github.com/KOMA-Inc/Galaxy">GitHub repository</a>.</p><p>That is all for now, hope you’ve found something interesting for yourself. Don’t hesitate to ask questions, propose improvements, or criticize the approach.</p><p>Here are some additional links I found useful:</p><ul><li><a href="https://www.youtube.com/watch?v=t7qjXViGOt0&amp;ab_channel=AYHAN">Star Shower Animation in SwiftUI Tutorial</a></li><li><a href="https://www.youtube.com/watch?v=z2MyaJZpnkk&amp;ab_channel=Kavsoft">Matrix Rain Effect</a></li><li><a href="https://www.youtube.com/watch?v=H-kWbiPqjuM&amp;t=1161s&amp;ab_channel=PaulHudson">Making it Rain — Advanced Special Effects with SwiftUI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bca890ca914" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>