ViewDidLoad中UIView的iOS界限

时间:2013-05-13 18:03:33

标签: ios null viewdidload bounds

我想使用UIView的边界来创建UILabel并将其添加到viewDidLoad方法中的UIView,但是,我发现在viewDidLoad中UIView的边界仍为null。但是当我看一个演示应用程序时,它的UIView的边界已经在viewDidLoad中初始化了。

在界面中我有

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

我正在尝试

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

但它不起作用,因为promotionView的边界为空。

1 个答案:

答案 0 :(得分:1)

您可以在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;
    }

}