2014-10-16 3 views
0

enter image description here 스크롤보기로 동적 버튼과 라벨을 만들고 있는데 자동 레이아웃을 설정하고 싶습니다. 가능한 여러 개의 동적 버튼을 설정합니다 .i 많은 자습서를 검색하지만 자동 레이아웃 설정을위한 예제가 없습니다. 여러 동적 버튼. 작업은하지만 모든 버튼이 함께 설정됩니다. 단 하나의 버튼과 레이블 만 표시합니다. 하지만 나는 정확한 결과를 검색하고 있지만 자동 레이아웃은 작동하지 않습니다. 무슨 문제동적으로 생성 된 버튼에 자동 레이아웃을 설정하는 방법은 무엇입니까?

-(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]; 


} 
+0

https://github.com/smileyborg/PureLayout 예를 살펴보십시오. – pqteru

+0

감사하지만, 몇 가지 간단한 예제가 있습니다 –

+0

문제는 모든 버튼이 함께 설정되어 마지막 버튼 만 표시되지만 버튼을 검색 할 때 올바른 결과가 표시된다는 것입니다. 무엇이 문제입니까 –

답변

1

검색 막대 코드의 사용 방법과 마찬가지로 프로그래밍 방식으로 제약 조건을 추가해야합니다. 그것을 이해하지 못하고 어딘가에서 코드를 복사 했습니까?

등이 많은 많은 자습서가 있습니다 : https://medium.com/@jsleeuw/mastering-programmatic-auto-layout-b02ed2499d79

이 같은 귀하의 모든 자동 레이아웃 제약 조건을 만들어야합니다 : 또한 시각적 형식

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

있습니다

이미있는 당신을 코드에 샘플이 있습니다.

질문을 편집하여 텍스트를 정리하고 코드를 읽을 수 있도록 포맷합니다. 사람들이 코드를 더 쉽게 읽을 수 있도록하기 위해 내가 한 변경 사항에 유의하십시오. 당신이 경우에 거의 4 일 (때로는 그들 중 하나가 문맥에 의해 추론)을 설정해야 자동 레이아웃으로

+0

이 코드는 단 하나의 버튼에 대해서만 알고 있습니다. 단 하나의 버튼으로 설정하는 방법을 알고 있습니다.내가 만든 복수의 버튼을 설정하고 싶습니다. –

+0

@ChetanGharat 여러 개의 버튼이나 버튼 하나 하나에 차이가 없습니다. 코드는 동일합니다. 각 버튼에 대해 제약 조건 세트를 제공해야합니다. –

+0

그렇지만 83 개의 버튼을 만들었고 그 때마다 제약 조건을 설정해야합니다 ........ –

0

:

  1. X
  2. Y는
  3. 높이
  4. 좌표 좌표

코드를 보면이 줄이 있습니다.

[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]; 

같은 것을해야한다, 당신은 적어도 오른쪽, 하단에 왼쪽, 위쪽과 맨 마지막 버튼에 매우 주먹 버튼을 고정한다. (단지 위쪽 예) 각면 같은 뭔가

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

는 희망이 도움이!

관련 문제