0

我在故事板中有一个 ViewController,它由两个 UIView 和底部的一个表组成。屏幕的中心包含一个在故事板中定义的 UIView,带有一个名为 middleSectionView 的出口。我想以编程方式将 subView 添加到 middleSectionView。以编程方式添加的 subView 未出现。这是我的代码:

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
    ...
}   
4

1 回答 1

2

您看不到的原因RoundedRect是您调用了错误的初始化程序:这一行

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

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

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

并将所需的框架坐标代替...上述坐标。

于 2013-03-03T19:28:25.927 回答