2013-10-26 5 views
0

Я много раз пытался создать представление таблицы и удалить определенные строки, я даже задал этот вопрос здесь раньше, и реализовать то, что они советовали, но пока не удалось даже получить мой столUITableView не входит в режим редактирования

ViewController .h

@interface XYZViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 

     @property (strong, nonatomic) UITableView *myTable; 
     @property (strong, nonatomic) NSMutableArray *names; 
     @property (weak, nonatomic) IBOutlet UIBarButtonItem *editButton; 

    - (IBAction)editMyTable:(id)sender; 

    @end 

ViewController.m

@implementation XYZViewController 

@synthesize names, myTable, editButton; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    //input values into the mutable array 
    names = [[NSMutableArray alloc]initWithObjects: 

      @"Bob", 
      @"Chris", 
      @"Tom" 

       , nil]; 

    editButton = self.editButtonItem; 

} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 

    return 1; 

} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 

    return @"Friends"; 

} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return [self.names count]; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    //create an identifier 
    static NSString *identifier; 

    //create the cell with the identifier 
    UITableViewCell *cell = [myTable dequeueReusableCellWithIdentifier:identifier]; 

    //check if cell is nil 
    if (cell == nil) { 

     //assign cell 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; 

    } 

    //assign the names of the array to each cell 
    cell.textLabel.text = [names objectAtIndex:indexPath.row]; 

    return cell; 

} 

- (IBAction)editMyTable:(id)sender 
{ 

    [editButton setTitle:@"Done"]; 
    [myTable setEditing:YES animated:YES]; 

} 

- (void)setEditing:(BOOL)editing animated:(BOOL)animated { 

    [super setEditing:editing animated:animated]; 
    [myTable setEditing:editing animated:animated]; 

} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    return YES; 

} 

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    if (editingStyle == UITableViewCellEditingStyleDelete) { 

     //remove from array 
     [names removeObjectAtIndex:indexPath.row]; 

     //remove from tableView 
     [myTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

    } 

} 

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return NO; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 

изображение: http://postimg.org/image/g9wqwuo6v/

Любая помощь очень ценится! Заранее спасибо! :)

+0

Правильно ли подключен IBAction к кнопке «edit»? Также удалите переопределение «setEditing: animated:'. В вашем «IBAction» вы устанавливаете свойство редактирования таблицы. Нет причин для того, чтобы ваш VC мог переопределить это (его, вероятно, даже называют). – Firo

+0

Да, мой 'IBAction' настроен правильно. http://postimg.org/image/lduq1kd2p/ –

ответ

1

Похоже, что проблема заключается в том, что вы не подключили свой myTable. Это не IBOutlet, и нигде в вашем коде вы не установили соединение. Когда вы звоните [myTable setEditing:YES animated:YES];, он отправляет его в таблицу nil. Вы можете проверить это, распечатав значение myTable перед вызовом метода редактирования: NSLog(@"%@", myTable);.

Также вы должны удалить переопределение setEditing:animated:, так как вы являетесь подклассом UIViewController, а не подклассом UITableView. Просто сделать ваш первоначальный вызов в вашем IBAction должно быть достаточно.

+0

Вы правы, я ничего не получаю, когда регистрирую его. Тем не менее, я подключил свойство 'myTable': http://postimg.org/image/cdv33a8ix/ –

+0

Вы просто связали свой' делегат' и 'datasource'. Это просто используется для того, чтобы задавать вопросы. Вы не подключили его к свойству 'myTable', хотя ... Создайте' myTable' '' IBOutlet' (например, 'editButton') и соедините таблицу с этим свойством. Затем обращается к нему с помощью 'self.myTable'. – Firo

+0

Большое вам спасибо! : D –

Смежные вопросы