如何将视图定位为子视图?

时间:2012-03-27 20:14:02

标签: ios uiview

我想以编程方式在屏幕上将IB中准备的视图(带有标签和按钮的红色框)定位为Subview。定位与“蓝线”一起工作正常(实际上可能有更好的方法在视图上画一条线?!)。但是,如右图所示,“AttributeApertureView”视图对象的视图会粘到顶部,而不是跟随从y = 60开始的initFrame参数。

    //Add blue Line
CGRect lineB = CGRectMake(0, 48, bounds.size.width, 0.5);
UIView *secondLine = [[UIView alloc]initWithFrame:lineB];
[secondLine setBackgroundColor:[UIColor colorWithRed:0.396 green:0.796 blue:0.894 alpha:1]];
[[self view]addSubview:secondLine];


//Add Attribute Aperture
AttributeApertureView *aperture = [[AttributeApertureView alloc]initWithFrame:CGRectMake(0, 60, bounds.size.width, 50)]; 
[aperture setBackgroundColor:[UIColor redColor]];
[[self view]addSubview:aperture];

AttributeApertureView类中的Init函数。这基本上只应该使用IB接口加载相关的nib文件。

@implementation AttributeApertureView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"AttributeApertureView"
                                                owner:self
                                              options:nil];
    self = [nib objectAtIndex:0];
}
return self;
}

enter image description here

在屏幕上定位“光圈”视图的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

似乎调用loadNibNamed:会将视图的帧重置为nib中的内容。这应该有效:

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"AttributeApertureView"
                                            owner:self
                                          options:nil];
    self = [nib objectAtIndex:0];
    self.frame = frame;
}
return self;
}

因为self = [super initWithFrame:frame];设置了一次框架,但是self = [nib objectAtIndex:0];最终会再次更改它,因为您正在重置整个视图,因此您必须再次将框架设置为参数中的框架。 / p>