我正在我的应用项目中动态创建20个按钮现在我想为每个按钮设置图像,因为不是每个按钮的图像都不同。我尝试了很多解决方案但没有得到正确的结果。我实现了以下代码......
int yPossion = 150, xPossion = 44; int temp = 0;
UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
[self.view addSubview:scrollView];
for (int i = 0; i < [objectName count]; i++) {
SMSCat1 *cat = [objectName objectAtIndex:i];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setTranslatesAutoresizingMaskIntoConstraints:YES];
//Label Dynamic Code
UILabel *label = [[UILabel alloc] init];
[label setText:cat.Name];
[label setTextColor:[UIColor brownColor]];
label.font = [UIFont systemFontOfSize:12];
[label sizeToFit];
[label setFrame:CGRectMake(5, 44, 70, 60)];
[scrollView addSubview:label];
[aButton addSubview:label];
[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)];
}
}
} 请帮我完成这项任务。我在图像文件夹中添加了20个图像,但是如何为每个按钮设置该图像(我可以使用settag)。
答案 0 :(得分:0)
不要害怕问你是不是新人。看看其他人的代码和学习是我们如何在我们的工作中变得更好。您可以在此处找到问题的答案 - how to set auto layout for dynamically created buttons?希望这可以帮助您