UIImageView resizing issue in UIPageViewController

后端 未结 3 1402
悲哀的现实
悲哀的现实 2021-02-07 10:06

I\'m building a new app and wish to have a \"Welcome walkthrough\" at the beginning wherein I have a storyboard with a series of images presented in a UIPageViewController. I ha

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 10:19

    From your video, I noticed that your UIImageView is always "resized" at the top, not at the bottom. This is most certainly because of your autolayout constraint you call "Top Space to Top Layout Guide". While your UIImageView's view controller is being transitioned through your scrolling page view controller, it doesn't know where the top layout guide is, so its topLayoutGuide.length is 0. Only after the animation completes does the view controller get a positive value for topLayoutGuide.length. Yes, the page view controller should be a bit smarter than this, but it's not.
    You can either stop using the top layout guide and make an autolayout constraint relative to the top of its superview. Or you can continue to use the top layout guide but account for when it's length is 0. You can do this by making an outlet for your storyboard's NSLayoutConstraint and overriding viewWillLayoutSubviews() in your ViewController containing your UIImageViews:

    @IBOutlet weak var topSpaceToTLG: NSLayoutConstraint!
    var parentTLGlength: CGFloat = 20
    
    override func viewWillLayoutSubviews() {
        if self.topLayoutGuide.length == 0 {
            // Lengthen the autolayout constraint to where we know the 
            // top layout guide will be when the transition completes
            topSpaceToTLG.constant = parentTLGlength
        } else {
            topSpaceToTLG.constant = 0
        }
    }
    

    This will always put the top of your UIImageView at the top layout guide, assuming that the status bar is always 20 points. Before laying out subviews, it will check to see if the top layout guide length is 0 or not and adjusts your autolayout constraint accordingly. After the transition animation completes, layout is triggered again, and the top layout guide length will be the expected value, so the constraint constant can go back to 0. Even better than hardcoding the value is to pass in the parent view controller's exact length during initialization, accounting for any possible changes to the top layout guide like adding a navigation bar.

提交回复
热议问题