简体   繁体   中英

How to get the height of a view that has been stretched by constraints? - iOS

I have following view hierarchy:

  • Root View
    • Child View

The root's height and width have been stretched by constraints (Top, Bottom, Leading, Trailing) and should be about 500. The height of the child is set by constraints too, so it should also equal 500.

Everything looks fine visually, but when I access the frame.bounds.height of the child it returns me the height of the whole screen, rather than the estimated 500. Even worse, when I access the frame.bounds.height on the Rootview it returns me 0 because I have set the frame to .Zero.

My question now is, how can I get the width and height from a view, that has been stretched out by constraints? It seems to me that .frame.bounds does not work with autolayout.

Showcase:

    print("collectionView height: ", String(describing: collectionView.frame.height) )

cv height: 0.0

CollectionView is the brown view:

在此处输入图片说明

My main objective was to make a cell as big as the brown collectionView. But this failed because I could not get the width of the dynamically sized collectionView.

Based on the comments, it looks like I helped solved the issue. It gets down to the view controller "life cycle", and exactly when "frames" are known".

The abbreviated lifecycle is:

  • viewDidLoad
  • viewWillAppear
  • viewWillLayoutSubviews
  • viewDidLayoutSubviews
  • viewDidAppear

A simple check - using the console and/or breakpoints - of this will show a few things:

  • while viewDidLoad knows of bounds, it know nothing of frames.
  • viewWillLayoutSubviews may know of frames, but it's also called (usually) more than once. - viewDidLayoutSubviews` while *possibly called more than once, is the earliest moment for a "guarantee" of frame size.

I was asked to post this as an answer, but I was looking for better sources here. I found two - and both are part of the same question.

UIViewController lifecycle

The top three answers are all good (I prefer the third for the best match to this question.)

For this issue, it gets to knowing when you can be sure frame size is known. It's possible that viewWillLayoutSubviews may work, but if it works, viewDidLayoutSubviews is the best place for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM