IOS - 获取Xib帧大小

时间:2013-03-30 17:36:00

标签: ios uiview frame xib addsubview

在myViewController.m中我试图添加一个名为 AlbumView 的自定义UIView作为子视图:

-(void)viewDidLoad {

 AlbumView *album = [[AlbumView alloc]init];

 [self.view addSubView:album];

 NSLog(@"album-frame: %@",NSStringFromCGRect(album.frame));

}

NSLog正在打印: album-frame:{{0,0},{0,0}}

由于AlbumView类具有以下Xib,并且在构建和运行我的应用程序时仍然可以看到它的大小正确,即使我没有使用任何initWithFrame:方法来初始化它。所以我想知道:

- 为什么在viewDidLoad(或viewDidAppear)中使用NSLogging时无法访问正确的帧大小?

enter image description here

编辑:以下是Xib类 - AlbumView.m

-(void)setupView{

    [[NSBundle mainBundle] loadNibNamed:@"AlbumView" owner:self options:nil];
    [self addSubview:self.view]; //where self.view is IBOutlet connected with the actual Xib view I posted above 


}

-(id)initWithFrame:(CGRect)frame{
    if((self = [super initWithFrame:frame])){
        [self setupView];
    }

    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    if((self = [super initWithCoder:aDecoder])){
        [self setupView];
    }

    return self;
}


- (void) awakeFromNib
{
    [super awakeFromNib];

    [self addSubview:self.view];
}

2 个答案:

答案 0 :(得分:2)

您通过向AlbumView发送init消息来初始化initWithFrame:CGRectZero,这相当于发送-(void)setupView{ [[NSBundle mainBundle] loadNibNamed:@"AlbumView" owner:self options:nil]; // Make my frame size match the size of the content view in the xib. CGRect newFrame = self.frame; newFrame.size = self.view.frame.size; self.frame = newFrame; [self addSubview:self.view]; //where self.view is IBOutlet connected with the actual Xib view I posted above } 。然后,在加载笔尖之后,您没有做任何事情来更改框架以匹配xib的内容。试试这个:

{{1}}

答案 1 :(得分:1)

// AlbumView.h

+ (instancetype)getView;

// AlbumView.m

+ (instancetype)getView {
    return [[[UINib nibWithNibName:@"AlbumView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
}

// myViewController.m

...

- (void)viewDidLoad {

 AlbumView *album = [AlbumView getView];

 [self.view addSubView:album];

 NSLog(@"album-frame: %@",NSStringFromCGRect(album.frame));

}

...