自定义的UIButton中的UITableViewCell - 删除不工作
我有一个自定义的UIButton我TableViewCell通过:自定义的UIButton中的UITableViewCell - 删除不工作
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ident = @"indet";
cell = [tableView dequeueReusableCellWithIdentifier:ident];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease];
}
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame: CGRectMake(230.0f, 7.5f, 43.0f, 43.0f)];
[button setImage:[UIImage imageNamed:@"check_bak.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(removeEntry) forControlEvents:UIControlEventTouchUpInside];
button.tag = [indexPath row];
[cell addSubview:button];
cell.textLabel.text = [myArray objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:20.0];
cell.textLabel.shadowColor = [UIColor whiteColor];
cell.textLabel.shadowOffset = CGSizeMake(0,1);
return cell;
}
我宣布我的.h为removeEntry功能indexPath。
removeEntry:
[myArray removeObjectAtIndex:indexPath.row];
[myTable reloadData];
myArray的是一个的NSMutableArray。
这种方式无法正常工作。
每次我在indexPath.row删除一个条目,它都会删除一个条目。但是错误的。它总是一个条目上面被删除。即使我做indexPath.row + 1/-1。
还有别的办法吗?按钮应该留在单元格中。
我希望这是可以理解的,对不起,我是德国人。 :)
您的表视图中有多少节?在您的removeEntry方法中将indexPath.row的值输出到控制台可能是一个好主意。如果您点击第一行,是否打印出0?第五行,正在打印出4等。
编辑:看你的代码,你存储的indexpath作为按钮的标记。在这种情况下,改变你的removeEntry方法,看起来像这样(你可以改变你返回类型为任何你想要返回):
- (void)removeEntry:(id)sender {
和“removeEntry”后添加一个冒号,当你将你的目标:
[button addTarget:self action:@selector(removeEntry:) forControlEvents:UIControlEventTouchUpInside];
现在,里面removeEntry,你可以这样做:
UIButton *button = (UIButton *)sender;
[myArray removeObjectAtIndex:button.tag];
[myTable reloadData];
使用下面的代码和平
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ident = @"indet";
cell = [tableView dequeueReusableCellWithIdentifier:ident];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease];
}
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
//below here your piece of code.
}
原因在于,在该方法中,我们重用了单元格,该单元格保留添加到单元格的所有子视图,并仅刷新单元格的文本部分。
希望这会对你有用!
我已经在我的iOS与编码的UITableView遇到同样的问题。 我已经通过在cell.contentView上添加按钮并从cell.contentView中删除它来修复它。
与
[cell.contentView addSubview:button];
代替[细胞addSubview:按钮]添加按钮;
在将视图添加到单元格以将单元格中的按钮删除之前,将以下代码行添加到cellForRowIndexPath()方法中。
for(UIView *subview in [cell.contentView subviews]){
[subview removeFromSuperView];
}
它会正常工作。
你如何将'indexPath'传递给你的'removeEntry'方法,以及你如何调用它? – benwong 2011-03-28 22:55:32