繁体   English   中英

使用Autolayout的XIB中的UIView总是600x600

[英]UIView in XIB using Autolayout is always 600x600

我创建了一个单独的.xib,因为我想在autolayout之外设计一个带autolayoutUIView 我使用wCompact hRegular创建了.xib,添加了UIView和约束。 简单。

在此输入图像描述

然后将它添加到viewDidLoad viewController

UIView *header = [[[NSBundle mainBundle] loadNibNamed:@"HeaderSearch" owner:self options:nil] lastObject];
NSLog(@"%@", NSStringFromCGRect(header.frame));
[self.view addSubview:header];

但是,当它添加时,帧大小为600x600,我无法弄清楚原因。

我在这里犯了什么错误,迫使这个奇怪的大小?

您需要在xib中取消选中“使用大小类”

取消选中大小类

视图框尺寸将是您设置的尺寸,而不是600x600

请参考这个。

header.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:header];

NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:header attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0];
[self.view addConstraint:widthConstraint];

NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:header attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:130.0];
[self.view addConstraint:widthConstraint];
[self.view addConstraint:heightConstraint];

如果是Xcode 8,则禁用“使用特征变体”

在此输入图像描述

我有类似的问题,但在我的情况下,我不喜欢关闭特征变化或大小类。 我也从XIB加载一些视图,但我使用这个方便的帮助器类别:

@implementation UIView (Initialization)

+ (instancetype)instantiateFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:nil options:nil] firstObject];
}

@end

我不想引入在代码中编写的约束,因此向我的视图控制器添加了一个覆盖viewWillLayoutSubviews方法,如下所示:

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self.firstView setFrame:self.view.bounds];
    [self.secondView setFrame:self.view.bounds];
}

在我的情况下, firstViewsecondView只是整个视图控制器的叠加层。

我认为,这是最正确的方法:

- (void)willMoveToParentViewController:(UIViewController *)parent {
    [super willMoveToParentViewController:parent];

    self.view.frame = parent.view.frame;
    [self.view layoutIfNeeded];

    // adjust subviews here
}

视图将获得正确的帧,并且在初始化时仅调用一次调整。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM