2012-07-23 87 views
0

我有一個使用故事板和ARC的iOS5項目。爲什麼我的UIButton不顯示在我的視圖中?

我有一個故事板與類thisViewController視圖,並在那裏我有一個較小的子視圖,我拖入並給它類thisView。

此視圖有一個自定義drawRect函數,它工作並繪製我想要的。 但我也想動態添加按鈕,所以我會在thisView的initWithFrame方法如下所示添加它們:

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     NSLog(@"This is called <3"); 
     UIButton *btn= [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     btn.frame = CGRectMake(0, 0, 50, 50); 
     btn.backgroundColor = [UIColor redColor]; 
     [btn setTitle:@"Play" forState:UIControlStateNormal]; 
     [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside]; 
     [self addSubview:btn]; 
     [self bringSubviewToFront:btn]; // last thing I tried, didn't work, thought z-index was to low or something 
    } 
    return self; 
} 

功能正在因爲NSLog的顯示屏叫,但按鈕是無處可尋

- 編輯 -

額外信息:

ThisView.h

@interface RadarView : UIView <CLLocationManagerDelegate>{ 
    CLLocation *currentLocation; 
} 
+0

你試過'[self.view addSubview:btn];'? – janusbalatbat 2012-07-23 08:44:58

+0

@janusfidel我得到一個錯誤'屬性視圖找不到對象的類型ThisView *。但這是正常的權利?導致對象本身是一個視圖?沒有? – Spyral 2012-07-23 08:47:53

+0

它取決於你有什麼超類,你的超類在這裏? – janusbalatbat 2012-07-23 08:49:13

回答

0

我發現了什麼問題是由於一些評論和聊天

有沒有在radarviewcontroller,從而引發initwithframe,這令的NSLog顯示一個初始化,和的initWithCoder沒有使用,因此我沒有看到任何東西,那是問題,並且混雜了一些東西。感謝評論和幫助!

0

不要在init方法中添加SubView。 在- (void)layoutSubviews中添加子視圖。

- (void)layoutSubviews { 
     [super layoutSubviews]; 

     if (![self viewWithTag:12345]) { 
      UIButton *btn= [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
      btn.frame = CGRectMake(0, 0, 50, 50); 
      btn.tag = 12345; 
      btn.backgroundColor = [UIColor redColor]; 
      [btn setTitle:@"Play" forState:UIControlStateNormal]; 
      [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside]; 
      [self addSubview:btn]; 
     } 
    } 
+2

這絕對應該工作。沒有必要對此投票。如果你不得不downvote,然後張貼原因。是男人羨慕做這麼多東西。 – Roshit 2012-07-23 10:15:26

+0

沒有人需要解釋downvotes。但是每次視圖大小調整時,此方法都會添加一個新按鈕 - 例如,如果設備已旋轉。 – jrturton 2012-07-23 10:29:20

+0

您應該添加條件來檢查子視圖是否已經可用。例如:'if(![self viewWithTag:12345]){UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(0,0,50,50); btn.tag = 12345; [self addSubview:btn];}'這限制了標籤爲「12345」的「btn」,以便每次在視圖上進行交互時添加。相應地更新了上面的代碼。 – Roshit 2012-07-23 10:34:00