为什么view2不出现在这段代码中? (在UIView 1中加入UIView 2)

时间:2011-03-24 11:57:08

标签: iphone ios uiview addsubview

为什么view2不出现在这段代码中?在结果中,我看到显示的本地View1标签,顶部带有红色边框,并且在整个绿色边框内,但是我看不到view2?这是带有文本“View2标签文本”的标签,不会出现。

test11ViewController.m

@implementation test11ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    View1 *view1 = [[[View1 alloc] initWithFrame:CGRectMake(0.0, 0.0, 400, 100) ] autorelease];
    view1.layer.borderColor = [UIColor redColor].CGColor;
    view1.layer.borderWidth = 1;
    [self.view addSubview:view1];
}
@end

View1.m

@implementation View1
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Local Label
        CGFloat width = self.frame.size.width;
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, width, 30)] autorelease];
        label.text = @"View1 Label Text";
        label.layer.borderColor = [UIColor greenColor].CGColor;
        label.layer.borderWidth = 1.0;
        [self addSubview:label];

        // External - Label2
        View2 *view2 = [[[View2 alloc] initWithFrame:CGRectMake(0.0, 30, width, 30)] autorelease];
        [super addSubview:view2];   
    }
    return self;
}
@end

View2.m

@implementation View2
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        CGFloat width = self.frame.size.width;
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, width, 30)] autorelease];
        label.text = @"View2 Label Text";   // Does  NOT appear in output
        label.layer.borderColor = [UIColor blueColor].CGColor;
        label.layer.borderWidth = 1.0;
    }
    return self;
}
@end

2 个答案:

答案 0 :(得分:3)

view2实际上并没有将标签添加到自身。你错过了这个:

[self addSubview:label];

换句话说,试试:

@implementation View2
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        CGFloat width = self.frame.size.width;
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, width, 30)] autorelease];
        label.text = @"View2 Label Text";   // Does  NOT appear in output
        label.layer.borderColor = [UIColor blueColor].CGColor;
        label.layer.borderWidth = 1.0;
        [self addSubview:label];  // NEW LINE HERE
    }
    return self;
}
@end

答案 1 :(得分:0)

在...之后的测试视图控制器行中

[self.view addSubview:view1];

... ...添加

[self.view sendSubviewToBack:view1];

view2现在显示了吗?警告,将两个视图的alpha设置为0.5,以确保一个不会遮挡另一个。