Resize subview when superview finishes loading

别说谁变了你拦得住时间么 提交于 2021-02-17 07:12:31

问题


I know theres countless similar questions on this that either all result in using flexible height/width or setting translatesAutoresizingMaskIntoConstraints to false.

I have add a view using an extension I created:

extension UIView {
    func addView(storyboard: String, viewIdentier: String) {
        let story = UIStoryboard(name: storyboard, bundle: nil)
        let subview = story.instantiateViewController(withIdentifier: viewIdentifier)
        subview.view.frame = self.bounds
        self.addSubview(subview.view)
    }
}

If I use this to initialise a view, in the ViewDidAppear everything works fine. But if its in the view did load then the constraints are all over the place because the contrainView that contains the view has its own constraints that are not yet loaded.

I currently use like this:

@IBOutlet weak var container: UIView!

override func viewDidLoad() {
    container.addView(storyboard: "Modules", viewIdentifier: "subview")
}

I don't want to initialise the view in the ViewDidAppear because of reasons. Is there any way of fixing this so it works as expected? Or reload the subview constraints after the superview has loaded?

Also I've really tried using other solutions. I can't make this work so would really appreciate some help.


回答1:


There is no way to do things in the hard-coded manner your code proposes. You are setting the frame of the subview based on self.bounds. But in viewDidLoad, we do not yet know the final value for self.bounds. It is too soon.

The appropriate place to do something that depends on knowing layout values is after layout has taken place, namely in viewDidLayoutSubviews. Be aware that this can be called many times in the course of the app's lifetime; you don't want to add the subview again every time that happens, so use a Bool flag to make sure that you add the subview only once. You might, on subsequent resizes of the superview, need to do something else in viewDidLayoutSubviews in order to make appropriate adjustments to the subview.

But the correct way to do this kind of thing is to add the subview (possibly in viewDidLoad) and give it constraints so that its frame will henceforth remain correct relative to its superview regardless of when and how the superview is resized. You seem, in your question, to reject that kind of approach out of hand, but it is, nevertheless, the right thing to do and you should drop your resistance to it.



来源:https://stackoverflow.com/questions/47858625/resize-subview-when-superview-finishes-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!