简体   繁体   中英

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.

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;
    }

}

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