почему view2 не появляется в этом коде?(включая UIView 2 в UIView 1) - PullRequest
0 голосов
/ 24 марта 2011

Почему view2 не появляется в этом коде? В результате я вижу показанную локальную метку View1, сверху с красной рамкой и внутри общей зеленой рамки, однако ничего не вижу в view2? То есть метка с текстом «View2 Label Text», НЕ появляется.

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 ]

3 голосов
/ 24 марта 2011

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
0 голосов
/ 24 марта 2011

В строке вашего тестового представления контроллера после ...

[self.view addSubview:view1];

... add ...

[self.view sendSubviewToBack:view1];

Показывает ли теперь view2?В качестве предупреждения следует установить для обоих видов альфа значение 0,5, чтобы убедиться, что одно не заслоняет другое.

...