我以编程方式创建了 UILable
在 xib 文件中 - awakeFromNib
的类,我正在尝试获取 mainViewController.m
中的标签高度.我尝试使用 NSBundle
加载 xib 文件,但它没有工作。还有其他方法我应该加载它吗?我需要调用awakFromNib
在 viewDidLoad
.
这是我的代码:
- (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/