2012-01-08 102 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

相关问题