UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How can I make my View stop unnecessary rendering with using CustomType for Binding in SwiftUI?

Forums > SwiftUI

I hava a CustomType called AppData, and it look like this:

struct AppData {
    var stringOfText: String
    var colorOfText: Color
}

I am using this AppData in my Views as State or Binding, I have 2 Views in my project called: ContentView and another one called BindingView. In my BindingView I am just using Color information of AppData. And I am expecting that my BindingView render or response for Color information changes! How ever in the fact BindingView render itself even for stringOfText Which is totally unnecessary, because that data is not used in View. I thought that maybe BindingView not just considering for colorOfText but also for all package that cary this data and that is appData So I decided help BindingView to understand when it should render itself, and I make that View Equatable, But that does not helped even. Still BindingView refresh and render itself on changes of stringOfText which it is wasting of rendering. How can I solve this issue of unnecessary rendering while using CustomType.

ContentView

import SwiftUI

struct ContentView: View {

    @State private var appData: AppData = AppData(stringOfText: "Hello, world!", colorOfText: Color.purple)

    var body: some View {

        print("rendering ContentView")

        return VStack(spacing: 20) {

            Spacer()

            EquatableView(content: BindingView(appData: $appData))
            //BindingView(appData: $appData).equatable()

            Spacer()

            Button("update stringOfText from ContentView") { appData.stringOfText += " updated"}

            Button("update colorOfText from ContentView") { appData.colorOfText = Color.red }

            Spacer()

        }

    }
}

BindingView

struct BindingView: View, Equatable {

    @Binding var appData: AppData

    var body: some View {

        print("rendering BindingView")

        return Text("123")
            .bold()
            .foregroundColor(appData.colorOfText)

    }

    static func == (lhs: BindingView, rhs: BindingView) -> Bool {
        print("Equatable function used!")
        return lhs.appData.colorOfText == rhs.appData.colorOfText
    }

}

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.