0

2 つの UIView と下部のテーブルで構成されるストーリーボードに ViewController があります。画面の中央には、middleSectionView というアウトレットを持つストーリーボードで定義された UIView が含まれています。プログラムで 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
    ...
}   
4

1 に答える 1

2

が表示されない理由はRoundedRect、間違った初期化子を呼び出しているためです: この行

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

initWithFrame:ビューを初期化するすべての作業を行うイニシャライザを呼び出しませんRoundedRect。呼び出しを次のように変更する必要があります

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

フレームの目的の座標を...上記の代わりに配置します。

于 2013-03-03T19:28:25.927 に答える