iOS:在单独的UIView中获取约束后的子视图宽度
我当前有一个链接到ViewController(.h和.m)的故事板。在故事板(主视图)中,我创建了另一个UIView,它占据了大约一半的顶部屏幕。我已将其分配给自定义类。自定义类有一个.h.m和XIB文件。自定义类中的特定代码片段包含以下内容:iOS:在单独的UIView中获取约束后的子视图宽度,ios,objective-c,uiview,Ios,Objective C,Uiview,我当前有一个链接到ViewController(.h和.m)的故事板。在故事板(主视图)中,我创建了另一个UIView,它占据了大约一半的顶部屏幕。我已将其分配给自定义类。自定义类有一个.h.m和XIB文件。自定义类中的特定代码片段包含以下内容: - (id)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder]; if (self){ [[NSBundle mainBundle]
- (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宽度。但从理论上讲,这些限制条件将生效,并将宽度设置为设备的大小,例如600px。所以我的问题是,如何找到更新的宽度
我试过:
[self setNeedsLayout];
[self layoutIfNeeded];
它们似乎不起作用。你能提出一些建议吗
-(void)layoutSubviews
{
[super layoutSubviews];
NSLog(@"Width before: %f",self.bounds.size.width);
NSLog(@"Height After: %f",self.bounds.size.height);
}
这将提供实际大小您是否尝试在LayoutSubview中执行此操作