2012-01-08 51 views
0

我有一個表視圖。和IM添加兩個按鈕,每個單元:以編程方式添加UIButton時出現UITableView錯誤

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     newBtn = [[UIButton alloc]init]; 
     newBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [newBtn setFrame:CGRectMake(250,10,25,55)]; 
     [newBtn addTarget:self action:@selector(addLabelText:) forControlEvents:UIControlEventTouchUpInside]; 
     [newBtn setTitle:@"+" forState:UIControlStateNormal]; 
     [newBtn setEnabled:YES]; 
     newBtn.hidden = YES; 
     [cell addSubview:newBtn]; 

     subBtn = [[UIButton alloc]init]; 
     subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [subBtn setFrame:CGRectMake(280,10,25,55)]; 
     [subBtn addTarget:self action:@selector(subtractLabelText:) forControlEvents:UIControlEventTouchUpInside]; 
     [subBtn setTitle:@"-" forState:UIControlStateNormal]; 
     [subBtn setEnabled:YES]; 
     subBtn.hidden = YES; 
     [cell addSubview:subBtn]; 

    } 
return cell; 
} 

,我想有隱藏在第一按鈕,那麼當表處於「編輯」模式,我想這些按鈕出現。當表格離開「編輯」模式時,按鈕消失。

我可以得到一個單元格按鈕來做到這一點。

- (IBAction)editButton:(id)sender 
{ 
    if (self.editing) 
    { 
     [self setEditing:NO animated:YES]; 
     [self.myTableView setEditing:NO animated:YES]; 
     EditButton.title = @"Edit"; 
     subBtn.hidden = YES; 
     newBtn.hidden = YES; 
    } 
    else 
    { 
     [self setEditing:YES animated:YES]; 
     [self.myTableView setEditing:YES animated:YES]; 
     EditButton.title = @"Done"; 
     subBtn.hidden = NO; 
     newBtn.hidden = NO; 
    } 
} 

但問題是:當我這樣做時,只有非常最後的單元格獲取按鈕。它們在我想要的時候出現和消失,但只有最後一個細胞!沒有其他細胞得到任何按鈕,有人可以幫助我!非常感謝!

回答

1

你這樣做的方式subBtnnewBtn指向最後一個單元格的按鈕。更好的方法是將子類UITableViewCell並創建按鈕實例變量。然後覆蓋- (void)setEditing:(BOOL)editing animated:(BOOL)animated並在那裏隱藏/顯示按鈕。

+0

你能解釋一下這個好一點嗎?我是一個新手!大聲笑你是什麼意思的「subcall」?如果它沒有太多的麻煩,請你請提供一些示例代碼,這樣我可以研究它並在我的程序中使用它?謝謝您的幫助! – iProRage 2012-01-10 23:38:32

+0

另外,我的按鈕如何「點」到最後一個單元格的按鈕?我不知道它是什麼代碼!再次感謝! :D – iProRage 2012-01-12 00:58:50

+0

我的意思是'子類'。看看你每次做「subBtn = [[UIButton alloc] init];」你的指針顯然被覆蓋,所以最後它指向最後一個單元格的按鈕。不知道如何更好地解釋這一點。 – 2012-01-12 04:37:04

1

你是如何激發'編輯按鈕'的方法?如果您使用的是didSelectRowAtIndexPath,則只有所選行將顯示按鈕。您可以通過indexpath.row遍歷可見單元格,從而取消隱藏每一行。

+0

我只是從導航欄上的按鈕調用此方法,並感謝您的幫助! – iProRage 2012-01-10 23:37:13

相關問題