尝试使用VFL和Autolayout将视图居中时出错

时间:2014-06-20 07:50:18

标签: ios autolayout

我试图使用VFL在其超级视图中居中视图,这是我的代码:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // THE SUPERVIEW 
    UIView *sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, [self tableView:tableView heightForHeaderInSection:section])];
    sectionView.backgroundColor = [UIColor grayColor];

    // THE LABEL TO BE CENTERED
    UILabel *sectionTitle = [UILabel new];
    sectionTitle.translatesAutoresizingMaskIntoConstraints = NO;
    sectionTitle.Text = @"Generals";
    [sectionView addSubview:sectionTitle];

    // AUTOLAYOUT INFO 
    NSDictionary *viewsDictionary = @{@"label":sectionTitle, @"view":sectionView};
    NSArray *leftPosition = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[view]-[label]"
                                                                    options:NSLayoutFormatAlignAllCenterY
                                                                    metrics:nil
                                                                      views:viewsDictionary];

    [sectionView addConstraints:leftPosition];

    return sectionView;
}

使用此代码我收到此错误

2014-06-20 09:44:20.938 gogo[442:60b] *** Assertion failure in -[NSLayoutConstraint constant], /SourceCache/Foundation/Foundation-1047.25/Layout.subproj/NSLayoutConstraint.m:601
2014-06-20 09:44:24.651 gogo[442:60b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '(null)'

如果我仅使用"|"代替"view"来更改VFL以引用超级视图我不会收到任何错误,但垂直对齐不起作用。

对我做错了什么的任何想法?

1 个答案:

答案 0 :(得分:-1)

试试这个

 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
...

[sectionView addConstraint:[NSLayoutConstraint constraintWithItem: sectionTitle
                                                        attribute: NSLayoutAttributeCenterY
                                                        relatedBy: NSLayoutRelationEqual
                                                           toItem: sectionView
                                                        attribute: NSLayoutAttributeCenterY
                                                       multiplier: 1.0f
                                                         constant: 0.0f]];
}

编辑:

试过这个,UILabel自动居中Y:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// THE LABEL TO BE CENTERED
     UILabel *sectionTitle = [UILabel new];
     sectionTitle.Text = @"Generals";
     return sectionTitle;
}