在哪里添加topLayoutGuide约束代码
解
想出一个解决scheme,将下面的代码放在我的子类浏览控制器.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 } }
原始post
苹果公司的文档没有说清楚,哪里(哪个类,哪个方法)我应该把这段代码(不知道自己在代码中指代什么):
[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
可以引用一个视图控制器。 有了这个代码,你的视图就添加了约束条件,所以在调用layoutSubviews
时候可以设置子视图的布局。 如果你在viewDidLoad
方法中添加这个代码(我build议你把它添加到那里),你可以自己replacemyViewController
的出现