0

我面临一个小问题。我的单元格上有一个 UIButton ,按下时我希望删除单元格。我已经尝试过了,但给出了错误。

- (IBAction)deleteCell:(NSIndexPath *)indexPath {
MainViewController *view = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
[view.nameArray removeObjectAtIndex:indexPath.row];
[view.priceArray removeObjectAtIndex:indexPath.row];
[view.mainTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}

我有一种感觉,我没有正确指定 indexPath,不知道怎么做。

任何帮助表示赞赏!

4

2 回答 2

1

我会这样做的。我有自己的 MyCustomCell 类,其中每个单元格都有按钮。

//MyCustomCell.h

@protocol MyCustomCellDelegate <NSObject>

-(void)deleteRecord:(UITableViewCell *)forSelectedCell;

@end

@interface MyCustomCell : UITableViewCell {

}
@property (nonatomic, strong) UIButton *deleteButton;
@property (unsafe_unretained) id<MyCustomCellDelegate> delegate;
@end

//MyCustomCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
 {
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self) {
     self.deleteButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 44)];
    [self.deleteButton setTitle:@"Delete your record" forState:UIControlStateNormal];
    [self.deleteButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [self.deleteButton addTarget:self action:@selector(editRecord:) forControlEvents:UIControlEventTouchUpInside];
    }
 }

-(IBAction)editRecord:(id)sender {
    [self.delegate deleteRecord:self]; // Need to implement whoever is adopting this protocol
}

--

// .h

@interface MyView : UIView <UITableViewDataSource, UITableViewDelegate, MyCustomCellDelegate> {


NSInteger rowOfTheCell;

注意:不要忘记将委托 MyCustomCellDelegate 设置为您的单元格。

// .m

-(void)deleteRecord:(UITableViewCell*)cellSelected
{
     MyCustomCell *selectedCell = (MyCustomCell*)cellSelected;
     UITableView* table = (UITableView *)[selectedCell superview];
     NSIndexPath* pathOfTheCell = [table indexPathForCell:selectedCell]; //current indexPath
     rowOfTheCell = [pathOfTheCell row];  // current selection row

     [view.nameArray removeObjectAtIndex:rowOfTheCell];
     [view.priceArray removeObjectAtIndex:rowOfTheCell];
     [view.mainTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:pathOfTheCell]    withRowAnimation:UITableViewRowAnimationRight];
}
于 2013-02-27T03:42:10.307 回答
0

将参数作为整数传递。

- (IBAction)deleteCell:(NSInteger)indexPath {
MainViewController *view = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
[view.nameArray removeObjectAtIndex:indexPath];
[view.priceArray removeObjectAtIndex:indexPath];
[view.mainTable reloadData];
}
于 2013-02-27T04:10:22.927 回答