这是我的代码,出现48次(日历中每个按钮一个)。
calenderButton *a1 = [calenderButton buttonWithType:UIButtonTypeCustom];
[a1 makeFrame:CGRectMake(75, 50, 70, 70) number:1 color:[UIColor orangeColor]];
[self.view addSubview:a1];
我想要做的是把它放在“for循环”中,将“a1”改为“a2”,“a3”等,以减少代码量。我想我可以把它减少到6“for loops”。
如何让“a1”变成一个变量,我不仅可以参考上面的代码,还可以参考“for循环”? (for循环将是这样的:)
for(int i = 0, j=75; i < 7; i++, j+=75);
我知道我必须将“a”连接到整数“i”,但是如何将它放在消息中呢?
答案 0 :(得分:3)
即使您使用相同的(本地)变量,您的代码也会创建48个不同的按钮:
for (int i = 0; i < 48; i++){
calenderButton *a1 = [calenderButton buttonWithType:UIButtonTypeCustom];
[a1 makeFrame:CGRectMake(75, 50, 70, 70) number:1 color:[UIColor orangeColor]];
[self.view addSubview:a1];
}
如果要保留对按钮的引用,可以将它们存储在数组中:
self.buttons = [NSMutableArray array];
for (int i = 0; i < 48; i++){
calenderButton *a1 = [calenderButton buttonWithType:UIButtonTypeCustom];
[a1 makeFrame:CGRectMake(75, 50, 70, 70) number:1 color:[UIColor orangeColor]];
[self.view addSubview:a1];
[self.buttons addObject:a1];
}
然后像这样访问它们:
calenderButton *button = [self.buttons objectAtIndex:7]; // Or any other index
注意,您可以使用您提到的循环:
for(int i = 0, j=75; i < 7; i++, j+=75)
但我不确定这会产生48个按钮。
答案 1 :(得分:3)
您可以将按钮放入数组中,如下所示:
在标题中声明实例变量NSMutableArray *allButtons
,然后......
allButtons = [NSMutableArray array];
for(int i = 0, j=75; i < 7; i++, j+=75) {
calenderButton *cb= [calenderButton buttonWithType:UIButtonTypeCustom];
// Configure the button here...
// use values of i and j to call CGRectMake, or as you see fit
[allButtons addObject:cb];
}
现在你的所有按钮都在一个数组中。您可以通过索引或您可能需要的任何其他方式访问它们,例如快速枚举循环。