如何设置控件宽度50%的屏幕?

时间:2014-10-22 20:12:27

标签: ios objective-c autolayout

这是一件简单的事情,但让我发疯。我需要2个控件来填充每个屏幕宽度的50%(它们是并排的)但是我无法检测到如何这样做。

我尝试了数百次autolayout组合而没有成功。请指教。

1 个答案:

答案 0 :(得分:0)

以下带有自动布局的代码将始终确保您的框在宽度上占据其父视图的50%。

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectZero];
    view1.translatesAutoresizingMaskIntoConstraints = NO;
    view1.backgroundColor = [UIColor greenColor];
    [self.view addSubview:view1];

    UIView *view2 = [[UIView alloc] initWithFrame:CGRectZero];
    view2.translatesAutoresizingMaskIntoConstraints = NO;
    view2.backgroundColor = [UIColor redColor];
    [self.view addSubview:view2];

    NSDictionary *bindings = NSDictionaryOfVariableBindings(view1, view2);
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[view1][view2]|" options:0 metrics:nil views:bindings]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view1(200)]" options:0 metrics:nil views:bindings]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view2(200)]" options:0 metrics:nil views:bindings]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:view1
                                                          attribute:NSLayoutAttributeRight
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1.0
                                                           constant:0.0]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:view2
                                                          attribute:NSLayoutAttributeLeft
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1.0
                                                           constant:0.0]];

}

使用它的技巧是将第二个视图(控件)的左属性设置为父视图的centerX,将第一个视图(控件)的右属性设置为父视图centerX