2013-03-03 71 views
0

我在包含兩個UIViews和底部表格的故事板中有一個ViewController。屏幕的中心包含一個定義在故事板中的UIView,帶有一個名爲middleSectionView的出口。我想以編程方式向middleSectionView添加一個子視圖。沒有出現以編程方式添加的子視圖。這裏是我的代碼:以編程方式將子視圖添加到故事板中的預定義子視圖不起作用

RoundedRect.m: 
#import "RoundedRect.h" 

@implementation RoundedRect 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     NSLog(@"RoundedRect: initWithFrame: entering"); 
     UIView* roundedView = [[UIView alloc] initWithFrame: frame]; 
     roundedView.layer.cornerRadius = 5.0; 
     roundedView.layer.masksToBounds = YES; 
     roundedView.layer.backgroundColor = [UIColor redColor].CGColor; 

     UIView* shadowView = [[UIView alloc] initWithFrame: frame]; 
     shadowView.layer.shadowColor = [UIColor blackColor].CGColor; 
     shadowView.layer.shadowRadius = 5.0; 
     shadowView.layer.shadowOffset = CGSizeMake(3.0, 3.0); 
     shadowView.layer.opacity = 1.0; 
     // [shadowView addSubview: roundedView]; 
    } 
    return self; 
} 
@end 


.h: 
... 
@property (strong, nonatomic) IBOutlet UIView *middleSectionView; 

.m: 
... 
#import "RoundedRect.h" 
... 
- (void)viewDidLoad 
{ 
    RoundedRect *roundRect= [[RoundedRect alloc] init]; 
    roundRect.layer.masksToBounds = YES; 
    roundRect.layer.opaque = NO; 
    [self.middleSectionView addSubview:roundRect]; // This is not working 
    [self.middleSectionView bringSubviewToFront:roundRect]; 
    // [self.view addSubview:roundRect];    // This didn't work either 
    // [self.view bringSubviewToFront:roundRect]; // so is commented out 
    ... 
} 

回答

2

爲什麼你沒有看到RoundedRect的原因是,你在呼喚一個錯誤的初始化:這一行

RoundedRect *roundRect= [[RoundedRect alloc] init]; 

不會調用initWithFrame:初始化,做所有的工作初始化您的RoundedRect視圖。您需要將呼叫切換到

RoundedRect *roundRect= [[RoundedRect alloc] initWithFrame:CGRectMake(...)]; 

,並把該幀的期望座標位置上方...的。

+0

非常感謝您的快速回復!不過,我仍然對這一個感到困惑。添加子視圖在viewDidLoad中。 – user1509295 2013-03-03 22:15:32

+0

@ user1509295請看看編輯。 – dasblinkenlight 2013-03-03 22:27:24

+0

這樣做。非常感謝你! – user1509295 2013-03-04 12:40:23

相關問題