以编程方式将子视图添加到故事板中预定义的子视图不起作用

时间:2013-03-03 19:24:41

标签: ios storyboard addsubview

我在一个故事板中有一个ViewController,它包含两个UIViews和一个底部的表格。屏幕中心包含故事板中定义的UIView,其中有一个名为middleSectionView的插座。我想以编程方式将一个subView添加到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
    ...
}   

1 个答案:

答案 0 :(得分:2)

您没有看到RoundedRect的原因是您正在调用错误的初始值设定项:此行

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

不会调用initWithFrame:初始化程序来完成初始化RoundedRect视图的所有工作。您需要将呼叫更改为

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

并将所需的框架坐标放在上面...的位置。