我在xib文件中以编程方式创建了UILable
- 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
。
答案 0 :(得分:0)
我有最糟糕的运气加载笔尖和问题寻找一个简单的方法这样做。这对我来说过去很有用。
将此添加到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;
现在在视图控制器中执行此操作
customCell *cellVC = [[cutsomCell alloc] initWithNib];
我在这里找到了一个使用该示例here
的好链接