OGeek|极客世界-中国程序员成长平台

标题: iOS:在单独的 UIView 中获取约束后的 subview 宽度 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:58
标题: iOS:在单独的 UIView 中获取约束后的 subview 宽度

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

- (id)initWithCoderNSCoder *)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 并将其添加到我 Storyboard的 subview 中。我的问题与计算宽度有关。 UISearchBar 将宽度的参数设为:

self.bounds.size.width

这会计算在 Storyboard 中绘制的框架。但是,因为我的 Storyboard中的 UIView 有约束,所以框架不是最终宽度。例如。如果我在 Storyboard中绘制 200px 宽度,我的代码将检索 200 并将 UISearch 栏设置为 200 宽度。但从理论上讲,约束将起作用并将宽度设置为设备的大小,例如600 像素。所以我的问题是,我怎样才能找到更新后的宽度?

我试过了:

[self setNeedsLayout];
[self layoutIfNeeded];

他们似乎没有工作。请您提出想法吗?



Best Answer-推荐答案


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

}

这应该给你实际的大小

关于iOS:在单独的 UIView 中获取约束后的 subview 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322775/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4