找出解决方案,将以下代码放在我的子类导航控制器.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
}
}
Apple的doc并未明确表示我应该在哪个(哪个类,哪个方法)放置这段代码(不知道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
答案 0 :(得分:2)
在这种情况下,self
可以引用视图控制器。使用此代码,您正在为其视图添加约束,因此在调用layoutSubviews
时,可以在设置子视图时对其进行布局。如果您在viewDidLoad
方法中添加此代码(我建议您将其添加到那里),则可以myViewController
self
的出现次数