为什么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
查看1.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
最佳答案
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
关于iphone - 为什么view2没有出现在此代码中? (将UIView 2合并到UIView 1中),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5418716/