我遇到了一个小问题。我的单元格上有一个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,不知道如何。
感谢任何帮助!
答案 0 :(得分: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];
}
答案 1 :(得分:0)
将参数作为整数传递。
- (IBAction)deleteCell:(NSInteger)indexPath {
MainViewController *view = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
[view.nameArray removeObjectAtIndex:indexPath];
[view.priceArray removeObjectAtIndex:indexPath];
[view.mainTable reloadData];
}