ios - 如何获得从 awakeFromNib 到 mainViewController.m 的对象高度?

标签 ios objective-c xib awakefromnib

我以编程方式创建了 UILable在 xib 文件中 - awakeFromNib 的类,我正在尝试获取 mainViewController.m 中的标签高度.我尝试使用 NSBundle加载 xib 文件,但它没有工作。还有其他方法我应该加载它吗?我需要调用awakFromNibviewDidLoad .

这是我的代码:

- (void)awakeFromNib
{
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 200)];
    [self.label setText:@"This is a label"];
    [self.myView addSubview:self.label];

    NSLog(@"%f", self.label.frame.size.height);  // Results: 200.0000
}
mainViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [[[NSBundle mainBundle] loadNibNamed:@"customCell" owner:self options:nil]objectAtIndex:0];
    customCell *cellVC = [[cutsomCell alloc] init];

    NSLog(@"%f", cellVC.label.frame.size.height); // Results: 0.0000
}

我需要 NSLog显示 200 ,而不是 0 .

最佳答案

我在加载 Nib 时遇到了最糟糕的运气,并且在寻找一种简单的方法时遇到了问题。这就是过去对我有用的方法。

将此添加到 customCell.m

- (id)initWithNib
{
    // where MyCustomView is the name of your nib
    UINib *nib = [UINib nibWithNibName:@"customCell" bundle:[NSBundle mainBundle]];
    self = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
    return self;
}

将此添加到 customCell.h
- (id)initWithNib;

现在在您的 View Controller 中执行此操作
customCell *cellVC = [[cutsomCell alloc] initWithNib];

我在这里找到了一个使用该示例的好链接 here

关于ios - 如何获得从 awakeFromNib 到 mainViewController.m 的对象高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28289194/

相关文章:

ios - 需要建议来处理许多应用内商店产品 (StoreKit)

iOS 正在播放类似于音乐/Spotify 应用程序的 View

ios - 返回 UITextView

ios - 如何添加 xib View 以查看 Controller swift 3

ios - 自动布局 View xib - 没有可编辑的约束?我需要居中元素

ios - 包含 UINavigationController 的状态栏大小不正确

iphone - ASIHTTPRequest调试

objective-c - 释放 Core Foundation 对象引用

cocoa - NSView 高级概述?

ios - Swift - 通过编辑更改保持小数点