Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

iphone - iOS Autolayout - Frame size not set in viewDidLayoutSubviews

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 correctly on the screen, but when I want to know the view's frame size, I don't get the right size.

For example: I press a key, the keyboard layout changes and layouts everything according to my constraints. Then I want to know the size of any button on the screen - I do that in "viewDidLayoutSubviews" and get that result in the console:

2014-10-29 12:27:09.088 Keyboard[2193:60674] view did layout subviews
2014-10-29 12:27:09.088 Keyboard[2193:60674] {{inf, inf}, {0, 0}}

The button has the correct size and correct position, but when trying to get its frame the size is not set.

Where do I have to put my code when it is not working in viewDidLayoutSubviews?

I found a lot of questions on stackoverflow and other websited, but none of them covered my question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...