从 xib 文件加载的自动调整视图大小
Posted
技术标签:
【中文标题】从 xib 文件加载的自动调整视图大小【英文标题】:autoresizing view loaded from xib file 【发布时间】:2014-05-14 07:56:56 【问题描述】:我的项目中有以下 Xib 文件:
我尝试向提示视图添加一些新的约束(超级视图的底部、顶部、左侧和右侧空间),但是从界面生成器中这是不可能的,如图所示。应该怎么做?
对应函数:
+ (instancetype)presentInViewController:(UIViewController *)viewController withDefaultsKey:(NSString *)defaultsKey
ELHintViewOwner *owner = [ELHintViewOwner new];
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:owner options:nil];
//hintViewOwner.decoupledView.delegateViewController = viewController
ELHintView *hintView = [bundle firstObject];
hintView.frame = viewController.view.bounds;
hintView.titleLabel.text = @"";
hintView.defaultsKey = defaultsKey;
hintView.tapAnywhereLabel.text = NSLocalizedString(@"Tap anywhere to continue", nil);
hintView.showLabel.text = NSLocalizedString(@"Don't show this message again", nil);
hintView.imageView.hidden = YES;
hintView.showSwitch.on = ![[[NSUserDefaults standardUserDefaults] valueForKey:defaultsKey] boolValue];
if ([hintView shouldShow])
[viewController.view addSubview:owner.decoupledView];
return hintView;
【问题讨论】:
您尝试向哪个视图添加约束,hintView 或 owner.decoupledView ? 我以为两者都一样 是的。它们是相同的:snag.gy/nG4QD.jpg 【参考方案1】:如果要将超级视图添加到其他视图,则必须在代码中添加自动布局约束。
+ (instancetype)presentInViewController:(UIViewController *)viewController withDefaultsKey:(NSString *)defaultsKey
ELHintViewOwner *owner = [ELHintViewOwner new];
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:owner options:nil];
//hintViewOwner.decoupledView.delegateViewController = viewController
ELHintView *hintView = [bundle firstObject];
hintView.frame = viewController.view.bounds;
hintView.titleLabel.text = @"";
hintView.defaultsKey = defaultsKey;
hintView.tapAnywhereLabel.text = NSLocalizedString(@"Tap anywhere to continue", nil);
hintView.showLabel.text = NSLocalizedString(@"Don't show this message again", nil);
hintView.imageView.hidden = YES;
hintView.showSwitch.on = ![[[NSUserDefaults standardUserDefaults] valueForKey:defaultsKey] boolValue];
if ([hintView shouldShow])
[viewController.view addSubview:owner.decoupledView];
hintView.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *constraintsX = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[hintView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(hintView)];
NSArray *constraintsY = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[hintView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(hintView)];
[viewController.view addConstraints:constraintsX];
[viewController.view addConstraints:constraintsY];
return hintView;
【讨论】:
还有其他方法吗?我尝试在界面生成器中做尽可能多的事情。以上是关于从 xib 文件加载的自动调整视图大小的主要内容,如果未能解决你的问题,请参考以下文章