How would you update a variable upon detecting a change in GeometryReader size?

Viewed 1501

I have a Geometry Reader in a .background of a Text view that saves the View size to a variable during .onAppear which works for the initial size calculation of the view. But if the view grows I cant think of a way for the Geometry Reader to update the size variable (taskHeight) of the view.

.background(
                    GeometryReader {geometry in
                        ZStack{
                            Rectangle()
                                .fill(Color.clear)
                                .onAppear{
                                    self.taskHeight = geometry.size.height      
                            }

                            // below is a function I created to try to get an updated taskHeight
                            // every time the String being typed updates, however including this
                            // gives me an error (written below the code snippet)

                            if (shouldCheckTaskSize())
                            {
                                self.taskHeight = geometry.size.height
                                Text("")
                            }

                        } //ZStack

                    }
            )

the function I've attemped to solve my problem with throws this error: "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"

and this is the function:

func shouldCheckTaskSize() -> Bool
{
    if (self.newTaskTitle != self.lastSizedTaskTitle)
    {
        self.lastSizedTaskTitle = self.newTaskTitle
        return true
    }
    else
    {
        return false
    }

}
1 Answers

In SwiftUI the view is just a function of the state if anything in the state changes the whole vie gets redrawn. So if the geometry changes the view will get redrawn automatically, just define the height of a view using geometry reader (if that is needed) and one of the modifiers and SwiftUI will do the work for you.

Related