スクロール ビューを使用して動的なボタンとラベルを作成しています。そのための自動レイアウトを設定します。複数の動的ボタンを設定できる方法.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];
}