1

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

-(void)viewDidLoad {

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

 [self.view addSubView:album];

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

}

NSLog 正在打印:专辑帧:{{0, 0}, {0, 0}}

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

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

在此处输入图像描述

编辑:以下是 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];
}
4

2 回答 2

2

您正在AlbumView通过向其发送init消息进行初始化,这相当于发送它initWithFrame:CGRectZero。然后,在您加载 nib 后,您无需更改框架以匹配 xib 的内容。试试这个:

-(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 
}
于 2013-03-30T18:46:25.403 回答
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));

}

...
于 2013-03-30T18:30:45.227 回答