2012-03-27 69 views
2

這是我的代碼,它發生48次(日曆中的每個按鈕一次)。如何用變量引用對象ID?

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); 

我知道我必須來串聯「一」與整數「i」,但我怎麼放置在該消息?

+0

你爲什麼要這麼做?如何比擁有一個或多個對象的數組更有利? – ColdLogic 2012-03-27 16:03:09

+0

還有http://stackoverflow.com/q/2283374/,http://stackoverflow.com/q/7758757/,http://stackoverflow.com/q/7601937/,http://stackoverflow.com/ q/8090590 /和其他與之相關的鏈接。 – 2012-03-27 17:12:38

回答

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

現在,所有的按鈕都在數組中。您可以通過索引或以您可能需要的任何其他方式訪問它們,例如用快速的枚舉循環。

+1

謝謝你......像一個冠軍! – SpokaneDude 2012-03-27 17:05:26

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個按鈕。

+0

sch:它如何添加48個不同的按鈕?每個人都必須有一個唯一的標識符,所以我可以參考它......在這種情況下,他們都被稱爲「A1」,對吧? – SpokaneDude 2012-03-27 16:06:56

+1

@ spokane-dude:實際上,沒有。這增加了48個不同的按鈕,因爲你創建了48個不同的按鈕該名稱在全局範圍內不唯一,僅在循環範圍內。要引用一個按鈕,你可以使用'[[self buttons] objectAtIndex:7];'這實際上就是你正在尋找的a7按鈕,但它不能通過'a7'指針來使用。 – ColdLogic 2012-03-27 16:12:02

+0

沒關係,我可以通過a7指針進行引用...我需要能夠從任何生成的按鈕添加和刪除對象(標籤和符號)... – SpokaneDude 2012-03-27 16:14:25