动态视图数的AutoLayout

时间:2014-01-09 15:47:35

标签: ios uiview ios7 autolayout

我在UIView底部有一个UIViewController,可以添加不同数量的视图。

NSUInteger letterCount = [word length];

        NSLog(@"The word letter count is: %ld",(unsigned long)letterCount);

        for (int i = 0; i < letterCount; i++) {
            NSLog(@"new view being created");

            UIView *letterTileView = [UIView autolayoutView];
            letterTileView.tag = 600 + i;
            [self.bottomBarView addSubview:letterTileView];
        }

这个词可以是任何单词,因此具有不同数量的字母。如果单词是APPLE,它将在底栏视图中创建5个子视图。

我想使用自动布局来布局这些视图。每个视图应为48x48(高x宽)。我希望这些子视图在底部栏视图中居中,并在它们之间填充。

我之前使用以下方法设置AL,但不确定如何处理动态情况并正确布局。

+ (NSArray *)constraintsWithVisualFormat:(NSString *)format  options:(NSLayoutFormatOptions)opts  metrics:(NSDictionary *)metrics  views:(NSDictionary *)views

2 个答案:

答案 0 :(得分:6)

以下是我的书中的一个示例,我以编程方式生成一堆UILabel,并在我进行时为它们添加约束。它与您的情况不同(我的标签是垂直排列的),但它显示了在动态创建界面时添加约束是多么容易:

UILabel* previousLab = nil;
for (int i=0; i<30; i++) {
    UILabel* lab = [UILabel new];
    // lab.backgroundColor = [UIColor redColor];
    lab.translatesAutoresizingMaskIntoConstraints = NO;
    lab.text = [NSString stringWithFormat:@"This is label %d", i+1];
    [v addSubview:lab];
    [v addConstraints:
     [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(10)-[lab]"
                                             options:0 metrics:nil
                                               views:@{@"lab":lab}]];
    if (!previousLab) { // first one, pin to top
        [v addConstraints:
         [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(10)-[lab]"
                                                 options:0 metrics:nil
                                                   views:@{@"lab":lab}]];
    } else { // all others, pin to previous
        [v addConstraints: 
         [NSLayoutConstraint
          constraintsWithVisualFormat:@"V:[prev]-(10)-[lab]"
          options:0 metrics:nil
          views:@{@"lab":lab, @"prev":previousLab}]];
    }
    previousLab = lab;
}

答案 1 :(得分:0)

我过去所做的是根据您拥有的观看次数动态创建可视格式字符串。一些示例代码:

NSArray *views = @[view1, view2, view3]; // this would be a dynamic array with views

NSMutableString *vflString = [NSMutableString string];
NSMutableDictionary *viewsDictionary = [NSMutableDictionary dictionary];
for (int i = 0; i < [views count]; i++) {
    NSString *viewIdentifier = [NSString stringWithFormat:@"view%d", i];
    [vflString appendString:[NSString stringWithFormat:@"-[%@]-", viewIdentifier];
    viewsDictionary[viewIdentifier] = views[i];
}

NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:vflString options:0 metrics:nil views:viewsDictionary];
[self.view addConstraints:constraints];

当然,您也可以更改指标和定位等内容。