2013-02-27 60 views
0

我面临一个小问题。我在我的单元格上有一个UIButton,当按下时,我希望单元格被删除。我试过这个,但是给出了错误。从UITableViewCell中删除单元格?

- (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,不知道如何。

任何帮助表示赞赏!

+0

什么是错误信息? – 2013-02-27 03:29:12

+0

indexPath的值是什么?你可以测试indexPath是否有效,然后删除该行,否则提醒“错误的选择” – 2013-02-27 03:34:04

+0

不是现在的计算机,而是关于声明一个UIButton,这导致我相信它的indexPath。 – ranjha 2013-02-27 03:34:29

回答

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]; 
} 
0

以整数形式传递参数。

- (IBAction)deleteCell:(NSInteger)indexPath { 
MainViewController *view = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil]; 
[view.nameArray removeObjectAtIndex:indexPath]; 
[view.priceArray removeObjectAtIndex:indexPath]; 
[view.mainTable reloadData]; 
} 
+0

这是他的问题。他无法获得正确的indexPath。那么他将如何将整数值传递给你的方法。 – 2013-02-27 04:16:42