解决方案
找到了一个解决方案,将以下代码放入我的子类导航 Controller .m 文件的 viewDidLoad
方法中:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
[[self view] setTranslatesAutoresizingMaskIntoConstraints:NO];
id topGuide = [self topLayoutGuide];
UIView * selfView = [self view];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (selfView, topGuide);
[[[self view] window] addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topGuide]-0-[selfView]"
options:0
metrics:nil
views:viewsDictionary]
];
[[[self view] window] layoutSubviews]; // You must call this method here or the system raises an exception
}
}
原帖
苹果的doc没有说清楚我应该把这 block 代码放在哪里(哪个类,哪个方法)(不知道代码中 self
指的是什么):
[button setTranslatesAutoresizingMaskIntoConstraints: NO];
id topGuide = myViewController.topLayoutGuide;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, topGuide);
[myViewController.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat: @"V: [topGuide]-20-[button]"
options: 0
metrics: nil
views: viewsDictionary]
self.view layoutSubviews; // You must call this method here or the system raises an exception
];
我觉得上面的代码块有一些拼写错误,所以我认为应该是这样的:
[button setTranslatesAutoresizingMaskIntoConstraints: NO];
id topGuide = myViewController.topLayoutGuide;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, topGuide);
[myViewController.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat: @"V: [topGuide]-20-[button]"
options: 0
metrics: nil
views: viewsDictionary]
];
self.view.layoutSubviews; // You must call this method here or the system raises an exception
最佳答案
在这种情况下,self
可以引用 View Controller 。使用此代码,您可以向其 View 添加约束,以便它可以按照您在调用 layoutSubviews
时设置的方式布局 subview 。如果您在 viewDidLoad
方法中添加此代码(我建议您在其中添加它),您可以将 myViewController
替换为 self
关于ios - 在哪里添加topLayoutGuide约束代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20418548/