我目前有一个故事板链接到ViewController(.h和.m)。在情节提要板(主视图)内,我创建了另一个UIView,它占据了顶部屏幕的一半。我已将其分配给自定义类。自定义类具有.h .m和XIB文件。我的自定义类中的特定代码片段包含以下内容:
- (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);
}
这应该给你实际的大小
关于ios - iOS:在单独的UIView中约束后获取SubView宽度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31322775/