简体   繁体   English

ViewDidLoad中的UIView的iOS范围

[英]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. 我想使用UIView的边界来创建UILabel并将其添加到viewDidLoad方法中的该UIView中,但是,我发现UIView的边界在viewDidLoad中仍然为null。 But when I look at a demo app, the bounds of its UIView is already initialised in viewDidLoad. 但是,当我看一个演示应用程序时,其UIView的边界已在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. 但是它不起作用,因为PromotionView的边界为null。

You can do it like this in viewDidAppear: 您可以在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;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM