2012-03-02 91 views
0

我以這種方式創建一個UIButton編程部分的內容的一部分編程方式創建:的UIButton在一個UITableView隱藏/顯示

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[button addTarget:self action:@selector(hideOrShowWithButtonId:)forControlEvents:UIControlEventTouchDown]; 

此按鈕的目的是,當它被按下時,內容在一個可用視圖中的部分消失,並且當點擊它時,內容返回。 所以單擊此按鈕時,它調用下面的功能: (注:self.cinemaButton,self.taxiButton和self.foodButton是字符串,不是按鈕),

-(void)hideOrShowWithButtonId:(id)sender; 
{ 
NSArray *dummy=[[[NSArray alloc] initWithObjects:nil] autorelease]; 
NSArray *dummy2=[[NSArray alloc] initWithObjects:self.cinemaButton,self.taxiButton,self.foodButton,nil]; 
NSLog(@"%@",self.taxiButton); 
if([[dummy2 objectAtIndex:[sender tag]]isEqual:@"Hide"]) 
{ 
    NSLog(@"Want to hide"); 
    [self.sections removeAllObjects]; 
    switch ([sender tag]) { 
     case 0: 
      [self.sections addObject:dummy]; 
      [self.sections addObject:self.taxiFavorite]; 
      [self.sections addObject:self.foodFavorite]; 
      [self.tableView reloadData]; 
      self.cinemaButton=[NSString stringWithString:@"Show"]; 
      break;    
     case 1: 
      [self.sections addObject:self.cinemaFavorite]; 
      [self.sections addObject:dummy]; 
      [self.sections addObject:self.foodFavorite]; 
      [self.tableView reloadData]; 
      self.taxiButton=[NSString stringWithString:@"Show"]; 
      break; 
     case 2: 
      [self.sections addObject:self.cinemaFavorite]; 
      [self.sections addObject:self.taxiFavorite]; 
      [self.sections addObject:dummy]; 
      [self.tableView reloadData]; 
      self.foodButton=[NSString stringWithString:@"Show"]; 
      break; 
    } 
    NSLog(@"%@",self.taxiButton); 
} 
else 
{ 
    NSLog(@"Want to show"); 
    switch ([sender tag]) { 
     case 0: 
      [self.sections replaceObjectAtIndex:0 withObject:self.cinemaFavorite]; 
      [self.tableView reloadData]; 
      self.cinemaButton=[NSString stringWithString:@"Hide"]; 
      break;    
     case 1: 
      [self.sections replaceObjectAtIndex:1 withObject:self.taxiFavorite]; 
      [self.tableView reloadData]; 
      self.taxiButton=[NSString stringWithString:@"Hide"]; 
      break; 
     case 2: 
      [self.sections replaceObjectAtIndex:2 withObject:self.cinemaFavorite]; 
      [self.tableView reloadData]; 
      self.foodButton=[NSString stringWithString:@"Hide"]; 
      break; 
    } 
} 
[dummy2 release]; 
NSLog(@"%@",self.taxiButton); 

}

的問題使用這個函數是字符串(例如在我的情況下:self.taxi)以值@「Show」退出,但當再次按下按鈕時,它的值爲@「Hide」 字符串的值self.taxibutton沒有改變。所以該功能只能隱藏該部分的內容而不再顯示它們。爲什麼會發生這種情況? 有沒有更簡單的方法來執行隱藏/顯示UItableView中特定部分內容的任務?

回答

1

在回答您的問題「是否有更簡單的方法」時,您可能需要查看來自Apple at this link的一些工作演示代碼。此代碼顯示如何具有可摺疊的部分。我試圖發展這個我自己,並且遇到了一些困難,然後才斷定我的問題被本代碼中使用的方法消除了。關鍵是維護一個包含每個部分信息的表格,包括指向每個部分的標題視圖的指針。我改編了這個演示代碼,並且它立即運行正常。你應該能夠自己編譯和運行代碼。

以下是一些不請自來的建議:如果您需要其他人查看並提供建議,則應爲變量選擇更多描述性名稱。 dummydummy2的目的並不明顯,它給人的直接印象是提供幫助將需要比應該做的更多的努力。