2011-06-01 27 views
2

在這裏,我有這樣的代碼,我試圖在那裏 openingHoursView.ohLocation有兩個值「VALUE1」和「值2」。 所以openingHoursView.idNum值爲「id1」和「id2」。 當我執行我的代碼時,我只能得到一個名稱爲「value2」和「id2」的按鈕。所以我的問題是如何創建的所有按鈕的openingHoursView.ohLocation價值觀和openingHoursView.idNum加入uibuttons編程

- (void)loadView { 

    storeAppDelegate = (StoreAppDelegate *)[[UIApplication sharedApplication] delegate];  

    int row = [storeAppDelegate.openingHoursLocationsDelegate count]-1; 
    for (int i = 0; i <= row; i++) { 
     openingHoursView = [storeAppDelegate.openingHoursLocationsDelegate objectAtIndex:i]; 

     self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 

     self.view.backgroundColor = [UIColor whiteColor]; 

     //create the button 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     //set the position of the button 
     if (i%2 != 0) { 
      button.frame = CGRectMake(30 , 100 , 150, 30); 

     }else { 
      button.frame = CGRectMake(30 , 100 + i*50, 150, 30); 
     } 


     //set the button's title 
     [button setTitle:openingHoursView.ohLocation forState:UIControlStateNormal]; 

     //listen for clicks 
     [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
     button.tag = [openingHoursView.idNum intValue]; 
     //add the button to the view 
     [self.view addSubview:button]; 
    } 
} 

-(IBAction) buttonPressed: (id) sender { 
    UIButton* button = (UIButton*)sender; 

    NSLog(@"User clicked %d", button.tag); 
    // Do something here with the variable 'sender' 
} 

只是一個解釋objectAtIndex:0 openingHoursView.ohLocation是「VALUE1」和objectAtIndex:1爲「值2「。對於openingHoursView.idNum

回答

3

問題同樣的程序是,你正在做的:

self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 

self.view.backgroundColor = [UIColor whiteColor]; 

for循環內,因此被覆蓋在每次迭代。您應該只在for循環前執行一次。

+0

Thx很多。不知道 – Spire 2011-06-01 11:52:34

3

您在

self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 

將這個代碼之前的for循環創建每個按鈕的新視圖。

2

UIButton * button = [[UIButtonalloc] init]; [selfview addsubView:button];