How do I use attributes of subviews within StackView set to Fill Proportionally as it recalculates after rotating device

244 Views Asked by At

I have implemented a stack view filled proportionally with images and labels and text and buttons inside of a popover over my primary view controller. When I segue to the popover I use the view will appear override to define the corner radius of the image that I call ProfileImage to be 1/2 its height so that it appears as a circle.

I when I rotate the device, the stack recalculates and changes the size of the profileImage. I have attempted to use the code below to adjust the corner radius so that it is a circle when the view transitions. I have tried this code in both the completion block and in the alongsideTransition block.

When I rotate the device the corner radius is set by the size of the image in the OLD orientation, not in the NEW orientation. It feels as though the transition to new orientation happens and THEN the stack recalculates itself. The corner radius seems to update before this happens. I would like help understanding how to call the height property of image that will be the height in the new view after the device rotates and the stack recalculates the image size based on that new orientation.

Thank you for any guidance you can provide. Please see below for the code in question:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { context in
        context.viewController(forKey: UITransitionContextViewControllerKey.from)
    }, completion: {(context) -> Void in
         self.view.layoutSubviews()
        self.ProfileImage.layer.cornerRadius = self.ProfileImage.bounds.size.height / 2
        print(self.ProfileImage.frame.size.height)
    })  
}
1

There are 1 best solutions below

0
On

An answer that is close but isn't perfect is to set the corner radius in viewWillLayoutSubviews() instead of in viewWillTransition() because the UIStack view lays out its subviews after the rotation not during it.

override func viewWillLayoutSubviews() {
   self.ProfileImage.layer.cornerRadius = self.ProfileImage.frame.size.height / 2 
}

thank you to the respondents to this article for pointing me in the right direction: View frame changes between viewWillAppear: and viewDidAppear:


My issue now is that somehow the size of the UIImage view has changed by a few pixels after the viewDidLayoutSubviews Call. Is there another function that would be called when a stack view or autolayout recaculates after the DidLayoutSubviews?

The app looks fine but there is some other behavior happening that I don't understand.