【问题标题】:How do I get an objects height from awakeFromNib to my mainViewController.m?如何获得从 awakeFromNib 到 mainViewController.m 的对象高度?
【发布时间】:2015-02-03 00:10:32
【问题描述】:

我以编程方式在 xib 文件中创建了一个 UILable - awakeFromNib 类,我试图在 mainViewController.m 中获取标签高度。我尝试使用 NSBundle 加载 xib 文件,但没有成功。还有其他方法我应该加载它吗?我需要在viewDidLoad 中致电awakFromNib

这是我的代码:

- (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

【问题讨论】:

  • customCell 是什么的子类?
  • customCell 链接到一个 xib 文件,其中包含一个单元格
  • 在 customCell.h 中它从 UIView 继承了什么?
  • UIView 是我在 xib/storyboard 文件中创建的一个对象。然后我创建了一个 IBOutlet,将其命名为 myView
  • 如果您将 cellVC 作为子项添加到您的 mainViewController 中,此标签会显示吗?

标签: ios objective-c xib awakefromnib


【解决方案1】:

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

将此添加到 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-06
    • 2013-11-02
    • 1970-01-01
    • 2013-12-27
    • 2012-10-10
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多