3

如何在 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];
}
4

3 回答 3

2

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

H:|-[view]-|

其次是

V:|-[view]-| 

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

于 2013-07-05T08:54:09.110 回答
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

于 2013-09-28T08:21:06.350 回答
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];

告诉我这是否是最好的方法。但它以任何方式工作。

于 2013-07-05T06:44:38.163 回答