Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is bounds and frame set for views/layers in Swift?

I have something like this in a UIView subclass:

override var bounds : CGRect {
  didSet {
    somelayer.frame = bounds
  }
}

In the corresponding somelayer, I have this:

override var bounds: CGRect {
  didSet {
    someFunction()
  }
}

Now if the view is initialized using super.init(frame: someFrame), the first block is not called. This appears to indicate that the bounds property is not set alongside frame.

If I change the first block to override var frame, then it will be called by super.init(frame: someFrame), and it will set the frame of somelayer. Interestingly, when that happens, the second block is called, suggesting that bounds and frame are set at the same time (which is what I'd expect, too).

Am I missing anything here?

like image 713
danqing Avatar asked Jun 12 '14 04:06

danqing


1 Answers

Property Observers are not called during initialization.

willSet and didSet observers are not called when a property is first initialized. They are only called when the property’s value is set outside of an initialization context.

Perhaps the way the view is being constructed internally, the frame is set post initialization but the bounds are not.

Then later, when setting the frame of the layer, the bounds are also updated by the internal method.

like image 72
drewag Avatar answered Oct 23 '22 01:10

drewag