Home > OS >  iOS SwiftUI - update variable based on view height on appear
iOS SwiftUI - update variable based on view height on appear

Time:09-19

I have this variable:

@State var profileViewHeight: CGFloat = 200

and I need to update it based on a view as soon as it appears

This is what I've tried:

    GeometryReader { geo in
        userProfileView(uid: uid, userid: self.$userid, offsetMenu: self.$offsetMenu, closeThisView: closeThisView)
            .frame(width: UIScreen.main.bounds.width)
            .background(Color.teal)
            .padding(.bottom, profileViewOffset)
            .offset(y: profileViewOffset)
            .zIndex(2)
        
        profileViewHeight = geo.size.height
    }

and I get the

Type '()' cannot conform to 'View'

error.

I also tried:

    .onAppear(){
        profileViewHeight = geo.size.height
    }

but the ui gets bugged this way.

Please help

CodePudding user response:

Ok I got it :D

.background(
    GeometryReader { geo in

        Color.clear
            .onAppear {
                profileViewHeight = geo.size.height
            }
    }
)

but it looks like it still creates an ui bug, I'll accept a solution which is better than this one

CodePudding user response:

What I meant :

GeometryReader { geo in
    userProfileView(uid: uid, userid: self.$userid, offsetMenu: self.$offsetMenu, closeThisView: closeThisView)
        .frame(width: UIScreen.main.bounds.width)
        .background(Color.teal)
        .padding(.bottom, geo.size.height)
        .offset(y: geo.size.height)
        .zIndex(2)
}

or

GeometryReader { geo in
    let profileViewHeight = geo.size.height
    userProfileView(uid: uid, userid: self.$userid, offsetMenu: self.$offsetMenu, closeThisView: closeThisView)
        .frame(width: UIScreen.main.bounds.width)
        .background(Color.teal)
        .padding(.bottom, profileViewOffset)
        .offset(y: profileViewHeight)
        .zIndex(2)
}

Try simple first

  • Related