2013-02-27 97 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