iOS Autolayout - Frame size not set in viewDidLayoutSubviews

后端 未结 2 995
北海茫月
北海茫月 2020-12-09 16:37

I\'m working on a keyboard for iOS 8 using Autolayout to place the buttons on the view.
When I\'m changing the layout using constraints, everything is appearing correctl

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 17:26

    I encountered a very similar issue (upvoted question) and found beeef's answer to point in the right direction. Given that Apple's documentation says not to call layoutSubviews() directly, I instead did as follows (where mySubView is a direct subview of self.view):

    override func viewDidLayoutSubviews() {
        // self.view's direct subviews are laid out.
        // force my subview to layout its subviews:
        self.mySubView.setNeedsLayout()
        self.mySubView.layoutIfNeeded()
    
        // here we can get the frame of subviews of mySubView
        // and do useful things with that...
    }
    

    Just FYI, in my case mySubView is a UIScrollView, and I need to get the frame of one of its subviews, such that I can set the contentOffset accordingly before the view appears. I'm not sure whether viewDidLayoutSubviews() is the best place to do this, but it ensures that mySubView has been laid out.

提交回复
热议问题