如何为动态创建的按钮设置自动布局?

时间:2014-10-16 08:15:02

标签: ios objective-c ios-autolayout

enter image description here   我正在创建带有滚动视图的动态按钮和标签,现在我想为它设置自动布局。它可能设置多个动态按钮.i搜索许多教程,但没有任何设置自动布局多个动态按钮的例子。工作但所有按钮设置在一起.means只显示一个按钮和标签。但我搜索它显示正确的结果,但自动布局不起作用。问题是什么

   -(void)DynamicButton:(NSMutableArray*)objectName
    {
     for(UIView *view in [scrollView subviews])
      {
        [view removeFromSuperview];
      }
      int yPossion = 100, xPossion = 44; int temp = 0;


      for (int i = 0; i<[objectName count]; i++)
     {
    SMSCategory *cat = [objectName objectAtIndex:i];

    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [aButton setTag:i];
    [aButton setTranslatesAutoresizingMaskIntoConstraints:YES];
    [aButton setBackgroundColor:[UIColor blackColor]];
    [aButton setBackgroundImage:[UIImage imageNamed:@"icon-menu.png"]  
    forState:UIControlStateNormal];

    [aButton setTitle:[NSString stringWithFormat:@"%d",i] 
    forState:UIControlStateNormal];

    [aButton setFrame:CGRectMake(xPossion, yPossion, 70, 60)];
     aButton.highlighted=YES;

    [scrollView addSubview:aButton];

    ;

    xPossion += aButton.frame.size.width+35;
    temp++;
    if (temp==3)
    {
        yPossion = aButton.frame.origin.y+aButton.frame.size.height+20;
        temp = 0;
        xPossion = 44;
        yPossion += aButton.frame.size.width-15;
        [scrollView setContentSize:CGSizeMake(scrollView.frame.size.width ,yPossion-
       50)];
    }

    UILabel *label =  [[UILabel alloc] init];
    [label setTranslatesAutoresizingMaskIntoConstraints:YES];

    [label setText:cat.Name];
    [label setTextColor:[UIColor blackColor]];
    label.font = [UIFont systemFontOfSize:12];

    [label sizeToFit];

    [label setFrame:CGRectMake(4, 44, 70, 60)];
    [scrollView addSubview:label];
    [aButton addSubview:label];

   }
   }

   //Autolayout code 
   [aButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSDictionary *viewsDictionary = @{@"aButton":aButton};

    // 2. Define the button Sizes
    NSArray *aButton_constraint_H = [NSLayoutConstraint 
                                     constraintsWithVisualFormat:@"V:[aButton(60)]"
                                                                        options:0
                                                                        metrics:nil
                                                                         views:viewsDictionary];

    NSArray *aButton_constraint_V = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[aButton(70)]"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:viewsDictionary];
    [aButton addConstraints:aButton_constraint_H];
    [aButton addConstraints:aButton_constraint_V];


    // 3. Define the views Positions using options
     NSArray *constraint_POS_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-80-[aButton]"
                                                                        options:0
                                                                        metrics:nil
                                                                        views:viewsDictionary];

     NSArray *constraint_POS = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[aButton]"
                                                                       options:0
                                                                       metrics:nil views:viewsDictionary];

    [self.view addConstraints:constraint_POS_V];
    [self.view addConstraints:constraint_POS];


}

2 个答案:

答案 0 :(得分:1)

您需要以编程方式添加约束,类似于您对searchBar代码的处理方式。您是否只是从某个地方复制了该代码而没有理解它?

有很多教程,例如:https://medium.com/@jsleeuw/mastering-programmatic-auto-layout-b02ed2499d79

您需要使用以下内容创建所有autoLayout约束:

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

还有一种可视化格式,您已经在代码中获得了样本。

我还编辑了您的问题以清理文本并格式化代码以使其可读。请注意我所做的更改,以便人们更轻松地阅读您的代码。

答案 1 :(得分:0)

使用autolayout,您必须在几乎所有情况下设置4件事(有时其中一件是由上下文推断的):

  1. X坐标
  2. Y坐标
  3. 宽度
  4. 高度
  5. 所以,看看你的代码,你有这条线......

        [aButton setFrame:CGRectMake(xPossion, yPossion, 70, 60)];
    

    之前的建议并非完全错误。这些限制正是上述线的含义。问题是你应该将按钮固定在它的超视图上,以便超视图定义它的宽度和高度。在这种情况下,要定义scrollView contenSize。

    因此,在伪代码中,您应该执行类似

    的操作
    for each button
    aButton.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *viewsDictionary = @{@"aButton":aButton};
    // 2. Define the button width and height
    NSArray *aButton_constraint_H = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[aButton(60)]"
                                                                    options:0
                                                                        metrics:nil
                                                                         views:viewsDictionary];
    
    NSArray *aButton_constraint_V = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[aButton(70)]"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:viewsDictionary];
    [aButton addConstraints:aButton_constraint_H];
    [aButton addConstraints:aButton_constraint_V];
    

    之后,你应该至少将第一个按钮固定在Left,Top和最后一个按钮到Right,Bottom。 每个方面都有类似的东西(例子只是顶端)

    NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:abutton
                                                                         attribute:NSLayoutAttributeTop
                                                                            relatedBy:NSLayoutRelationEqual
                                                                               toItem:self.scrollView
                                                                            attribute:NSLayoutAttributeTop
                                                                           multiplier:1
                                                                             constant:0];
    

    希望它有所帮助!!