2013-05-13 33 views
1

我想使用UIView的界限來創建UILabel並將其添加到viewDidLoad方法內的UIView,但是,我發現UIView的邊界在viewDidLoad內仍爲null。但是當我看一個演示應用程序時,其UIView的邊界已經在viewDidLoad中初始化了。iOS的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的邊界爲空。

+0

更改此代碼'viewWillAppear'也檢查出口連接 – 2013-05-13 18:05:16

+0

promotionView'的'的邊界是不'nil'。它是'promotionView'本身是'nil'。確保你確實將'promotionView'設置爲正確的視圖。 – rmaddy 2013-05-13 18:06:49

+0

@MidhunMP將這樣的代碼放在'viewWillAppear'中是不合適的。如果其他視圖控制器從導航堆棧中彈出/彈出,則可以多次調用「viewWillAppear」。 – rmaddy 2013-05-13 18:07:30

回答

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

} 
+0

謝謝,這解決了我的問題,但我仍然很好奇,爲什麼我的UIView綁定在viewDidLoad中爲0,而演示代碼可以使用它。我使用這裏的演示代碼btw [鏈接](https://github.com/mpospese/MPFlipViewController) – harinsa 2013-05-13 18:35:52

+0

@ doog,它看起來像他在該演示中使用self.view.frame - 控制器的self.view不是沒有在viewDidLoad時,但你添加的子視圖。 – rdelmar 2013-05-13 18:42:21

+0

@doog,我應該在viewDidLoad中限定我對子視圖邊界爲0的評論 - 當自動佈局被打開(默認情況下)時,這是真實的,但是它會有你在故事板中設置的邊界,如果自動佈局已關閉。我總是把它留下,但是然後用約束而不是設置框架來確定視圖的大小。 – rdelmar 2013-05-13 19:32:22

相關問題