iOS: 在单独的UIView中获取约束后的SubView宽度

iOS: Get SubView width after constraints in a separate UIView

我目前有一个故事板链接到 ViewController(.h 和 .m)。在故事板(主视图)内,我创建了另一个 UIView,它占据了大约一半的顶部屏幕。我已将其分配给自定义 Class。自定义 class 有一个 .h .m 和 XIB 文件。我的自定义 class 中的特定代码片段包含以下内容:

- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self){
    [[NSBundle mainBundle] loadNibNamed:@"myXIB" owner:self options:nil];

    NSLog(@"Width before: %f",self.bounds.size.width);
    NSLog(@"Height After: %f",self.bounds.size.height);

    //[self setNeedsLayout];
    //[self layoutIfNeeded];

    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 44)];
    [self.view addSubview:searchBar];


    CGRect newFrame = self.view.frame;
    newFrame.size.width = self.bounds.size.width;
    newFrame.size.height = self.bounds.size.height;
    [self.view setFrame:newFrame];

    [self addSubview:self.view];
}
return self;
}

代码当前创建一个 UISearchBar 并将其添加到我的故事板中的子视图。我的问题与计算宽度有关。 UISearchBar 将宽度参数设为:

self.bounds.size.width

这会计算故事板中绘制的帧。但是因为我的故事板中的 UIView 有限制,框架不是最终的宽度。例如。如果我在故事板中绘制 200px 宽度,我的代码将检索 200 并将 UISearch 栏设置为 200 宽度。但理论上,约束会生效并将宽度设置为设备的大小,例如600 像素。所以我的问题是,如何找到更新后的宽度?

我试过:

[self setNeedsLayout];
[self layoutIfNeeded];

他们似乎没有用。你能提出一些想法吗?

-(void)layoutSubviews
{
    [super layoutSubviews];
    NSLog(@"Width before: %f",self.bounds.size.width);
    NSLog(@"Height After: %f",self.bounds.size.height);

}

这应该会给你实际尺寸