Ios 如何以编程方式使用自动布局?

Ios 如何以编程方式使用自动布局?,ios,layout,uiview,Ios,Layout,Uiview,当我尝试像这样使用自动布局时: CJGBoardLabels* labels = [CJGBoardLabels alloc]; [self.view insertSubview:labels aboveSubview:_mainBoard]; [_mainBoard addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[labels]|" options:NSLayoutFormatAlignAllCenterX

当我尝试像这样使用自动布局时:

CJGBoardLabels* labels = [CJGBoardLabels alloc];
[self.view insertSubview:labels aboveSubview:_mainBoard];
[_mainBoard addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[labels]|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(labels)]];
我得到这个错误:

2014-01-02 16:51:05.141 chess[18050:70b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Requesting the window of a view (<CJGBoardLabels: 0xa6a8570; frame = (0 0; 0 0); transform = [0, 0, 0, 0, 0, 0]; alpha = 0; opaque = NO; layer = (null)>) with a nil layer. This view probably hasn't received initWithFrame: or initWithCoder:.'
2014-01-02 16:51:05.141国际象棋[18050:70b]***由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因是:“请求具有零层的视图的窗口()。此视图可能尚未收到initWithFrame:或initWithCoder:。'
以编程方式使用自动布局而不调用initWithFrame的合适方法是什么?或者我还需要调用initWithFrame吗?

您需要这样做

labels = [CJBoardLabels new];

在每种情况下,后跟(重要)

或者,你可以使用

这为您完成了上述任务…还有许多其他的好东西,可以在代码中创建约束

labels = [[CJBoardLabels alloc] init];
labels = [[CJBoardLabels alloc] initWithFrame:CGRectZero];
labels.translatesAutoresizingMasksIntoConstraints = NO;
labels = [CJBoardLabels autolayoutView];