以编程方式添加 UIButton 时出现 UITableView 错误
Posted
技术标签:
【中文标题】以编程方式添加 UIButton 时出现 UITableView 错误【英文标题】:UITableView bug when adding a UIButton programmatically 【发布时间】:2012-01-08 23:35:48 【问题描述】:我有一个表格视图。我在每个单元格中添加了两个按钮:
- (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】:您执行此操作的方式subBtn
和newBtn
指向最后一个单元格的按钮。更好的方法是继承UITableViewCell
并制作按钮实例变量。然后覆盖- (void)setEditing:(BOOL)editing animated:(BOOL)animated
并隐藏/显示那里的按钮。
【讨论】:
你能解释一下吗?我是菜鸟!大声笑你所说的“子呼叫”是什么意思?另外,如果它不是太麻烦,您能否提供一些示例代码,以便我可以研究它并在我的程序中使用它?感谢您的帮助! 另外,我的按钮如何“指向”最后一个单元格的按钮?我不确定它是什么代码!再次感谢! :D 我的意思是“子类”。每次执行“subBtn = [[UIButton alloc]init];”时都要查看您的指针显然已被覆盖,因此最后它指向最后一个单元格的按钮。不知道如何更好地解释这一点。 好的,我明白你在说什么。但是,我不确定如何解决它。我应该在init
方法中分配和初始化按钮吗?感谢您的帮助!【参考方案2】:
您是如何触发“编辑按钮”方法的?如果您使用的是 didSelectRowAtIndexPath,那么只有选定的行会显示按钮。您可以遍历 indexpath.row 以获取可见单元格,取消隐藏每一行。
【讨论】:
我只是从导航栏上的按钮调用此方法,感谢您的帮助!以上是关于以编程方式添加 UIButton 时出现 UITableView 错误的主要内容,如果未能解决你的问题,请参考以下文章