3

I have a simple UIView subclass where I place a UILabel within, in order to give such UIView a certain frame, background color and text format for its label from a UIViewController.

I'm reading the View Programming Guide for iOS but there are some things that I'm not fully understanding... when your view has only system standard subviews, such my UILabel, should I override the drawRect: method? Or is that only intended for Core Animation staff? If I shouldn't setup standard subviews within such method, what is the correct place to do so? Should I then override the init method?

Thanks in advance

AppsDev
  • 12,319
  • 23
  • 93
  • 186

1 Answers1

2

No, you should not override the drawRect for initializing the sub views because it causes a performance hit. That should be done either in the init, initWithFrame, or initWithCoder methods. For example, this is how you do it using the initWithFrame method

- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
      //initialize sub views 
  }
  return self;
themobileapper
  • 184
  • 1
  • 4
  • 1
    Note that the `UIView` implementation of `init` just calls `initWithFrame` with a `CGRectZero`. You should therefore always override `initWithFrame` (or `initWithCoder` if you're using NSCoding). – Hamish Mar 14 '16 at 12:17
  • Thank you. Just another question came to me: what about setting the subviews by overriding the `layoutSubviews` method? Would that be more appropriate than setting them in the initialization method? – AppsDev Mar 14 '16 at 13:30
  • 2
    You should override `layoutSubviews` to perform any custom layout logic for your subviews, such as updating their frames. As it can be called multiple times during a `UIView`s lifetime, it's not appropriate for *initialising* the subviews themselves. This should be done in an initialiser. – Hamish Mar 14 '16 at 13:54
  • @Hamish what if for initialising some subviews you need to have the actual frame of the view? – StackGU Oct 27 '20 at 22:20