自动布局水平和垂直格式在一起

时间:2013-07-05 06:26:26

标签: iphone ios constraints autolayout

如何在constraintsWithVisualFormat中一起添加水平和垂直可视格式?只有横向。我想添加V:| -50- [leftButton]和V:| -50- [rightButton]。怎么做?创建另一个NSLayoutConstraint?

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [leftButton setTitle:@"Left" forState:UIControlStateNormal];
    [leftButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:leftButton];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [rightButton setTitle:@"Right" forState:UIControlStateNormal];
    [rightButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:rightButton];

    NSArray *layoutConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-50-[leftButton(>=80)]-50-[rightButton(>=80)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(leftButton, rightButton)];
    [self.view addConstraints:layoutConstraints];
}

3 个答案:

答案 0 :(得分:2)

您可以根据需要使用可视化格式创建任意数量的单独约束。您不能在同一个字符串中混合水平和垂直约束,但没有什么能阻止您创建:

H:|-[view]-|

其次是

V:|-[view]-| 

将每个VFL语句视为在superview的单个行或列中表达布局。

答案 1 :(得分:1)

哦,我想通了。我应该创建另一个这样的约束:

NSLayoutConstraint *leftButtonLayoutConstraint = [NSLayoutConstraint constraintWithItem:leftButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:10.0];
    [self.view addConstraint:leftButtonLayoutConstraint];

告诉我这是否是最好的方法。但它无论如何都可以。

答案 2 :(得分:1)

我为NSLayoutConstraint做了一个类别,它接受一个包含水平和垂直VFL声明的字符串,因为我注意到大部分时间我都需要(H:,V :)同一个对象

@implementation NSLayoutConstraint (CombinedVFL)

+(NSArray *)constraintsWithCombinedVisualFormat:(NSString *)combinedFormat views:(NSDictionary *)views
{
     int indexOfVerticalChar = [combinedFormat rangeOfString:@"V:"].location;
     NSString *verticalString = [combinedFormat substringFromIndex: indexOfVerticalChar];
     NSString *horizontalString = [combinedFormat substringToIndex: indexOfVerticalChar - 1 ]; // trim

     return [[self constraintsForString:horizontalString views:views] arrayByAddingObjectsFromArray:[self constraintsForString:verticalString views:views]];
}

+(NSArray *)constraintsForString:(NSString *)string views:(NSDictionary *)views
{
     return [NSLayoutConstraint constraintsWithVisualFormat:string options:0 metrics:nil views:views];
}

@end

致电:

[self addConstraints:[NSLayoutConstraint constraintsWithCombinedVisualFormat:@"H:|[topBorder]| V:|[topBorder(1)]" views:@{ @"topBorder" : topBorder}]];

我把代码放在我的github上:https://github.com/dannyshmueli/NSLayoutConstraint-CombinedVFL