Search code examples
iosnullviewdidloadbounds

iOS Bounds of UIView in ViewDidLoad


I wanted to use the bounds of a UIView to create a UILabel and add it to that UIView inside the viewDidLoad method, however, I have found that the bounds of UIView is still null inside viewDidLoad. But when I look at a demo app, the bounds of its UIView is already initialised in viewDidLoad.

In the interface I have

@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIView *promotionView;
@end

And I am trying to do

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *container = [[UIView alloc] initWithFrame:self.promotionView.bounds];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, container.bounds.size.height-100, 320, 20)];
    label.text = @"Promotion Title";
    [container addSubview:label];
    [self.promotionView addSubview: container];
}

but it doesn't work because the bounds of promotionView is null.


Solution

  • You can do it like this in viewDidAppear:

    -(void)viewDidAppear:(BOOL)animated {
        static int first = 1;
        if (first) {
            UIView *container = [[UIView alloc] initWithFrame:self.promotionView.bounds];
    
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, container.bounds.size.height-100, 320, 20)];
            label.text = @"Promotion Title";
            [container addSubview:label];
            [self.promotionView addSubview: container];
            first = 0;
        }
    
    }