0

How can I get the height of my custom control?

The idea is I will use it to dynamically set the height of some buttons inside the custom control. I've set the Placeholder height to 44 in the Xcode size inspector.

enter image description here

Working off Apple's Start Developing iOS Apps (Swift) tutorial, I am attempting to access frame.size.height and it gives a value of 1000 while the tutorial seems to suggest it should be 44.

class RatingControl: UIView {
    ...
    override public var intrinsicContentSize: CGSize {
        let buttonSize = Int(frame.size.height)
        print(buttonSize) // prints 1000
        let width = (buttonSize * starCount) + (spacing * (starCount - 1))
        return CGSize(width: width, height: buttonSize)        
    }
    ...
ThisClark
  • 14,352
  • 10
  • 69
  • 100

2 Answers2

2

You should never access frame inside intrinsicContentSize. intrinsicContentSize should return the size that perfectly fits the contents of the view, regardless of its current frame.

In your case, I think you can just use 44 for your buttonSize.

Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65
  • It's curious that Apple's writer accessed `frame` in that way in their tutorial. Setting the size to 44 works. I'll just go with it. – ThisClark Oct 16 '16 at 00:49
1

The placeholder intrinsic size is just that, placeholder, so that IB interpreter is has some value to work with and can layout the rest of the scene. But in your intrinsicContentSize getter, you implement the real size, which will be used in runtime by the AutoLayout engine. Since you return 1000 as the intrinsic content height, that's what you will see in runtime.

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
  • Where does the 1000 come from, and how can I get the 44 as it is set on the height property of the custom control? I would like to do something like `let buttonSize = /* wherever 44 is */` – ThisClark Oct 16 '16 at 00:41
  • In your `intrinsicContentSize` implementation, you return 1000. You say so yourself in the comment `// prints 1000`. – Léo Natan Oct 16 '16 at 00:42
  • 1
    Auto Layout can use whatever value for the view's initial size. It used to use the values coming from IB (interface builder), but starting from iOS 10, everything seems to be 1000. – Khanh Nguyen Oct 16 '16 at 00:44
  • 1000 comes from the decoder before layout. Placeholder values do not reach in anyway during decoding. – Léo Natan Oct 16 '16 at 00:45
  • @ThisClark See my answer here: http://stackoverflow.com/questions/22533418/ios-storyboards-nibs-low-level-anatomy-how-are-they-implemented/22583423#22583423 This will get you started. – Léo Natan Oct 16 '16 at 00:59