2011-12-07 44 views
1

我創建了一堆文本區域。我正在堆疊他們垂直,所以我使用:想創建一個變量,增加它並獲得新值

CGRectMake(193, ((i * 45) + 45), 240, 30) 

然後每個文本框創建後,我增加i。

int i = 0 

CGRect myRect = CGRectMake(193, ((i * 45) + 45), 240, 30) 
UITextField *myTextField01 = [[UITextField alloc] initWithFrame:myRect]; 
//format and add to view text field 
i++; 

//create next text field 
myRect = CGRectMake(193, ((i * 45) + 45), 240, 30) //can i get rid of this line? 

UITextField *myTextField01 = [[UITextField alloc] initWithFrame:myRect]; 
//format and add to view text field 
i++; 

我需要重新分配myRect得到我更新到1

值有沒有更好的辦法做到這一點,所以我不需要重新分配myRect獲得的更新值一世?

回答

2

CGRect是一個結構,這樣可以增加內部領域直接:

CGRect myRect = CGRectMake(193, 45, 240, 30); 
UITextField *myTextField01 = [[UITextField alloc] initWithFrame:myRect]; 

myRect.origin.y += 45; 
UITextField *myTextField02 = [[UITextField alloc] initWithFrame:myRect]; 

myRect.origin.y += 45; 
UITextField *myTextField03 = [[UITextField alloc] initWithFrame:myRect]; 

我也將使用循環和某種容器(可能NSArray)的,但是這是一個側面的話題;)

+0

這個效果很好,我不得不每次重新分配myRect,並用這個代替i ++。 – Padin215

+0

很高興爲您提供幫助,但我向您保證,重新分配CGRect結構的「成本」非常接近於零,您應該沒有理由擔心它。謹防[過早優化](http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize)! –

+0

呵呵,是不是我要優化,我只是厭倦了copyig /粘貼那麼多行= D – Padin215

2

每次使用myRect = CGRectOffset(myRect, 0, 45);。這裏不使用「i」,因爲你抵消了已經抵消的矩形。

+0

這工作擺脫int我,但我仍然需要在每個文本框後重新分配「myRect」。我希望不必這樣做。 – Padin215

相關問題