2013-08-22 6 views
0

У меня есть табличное представление, которое отображает список «избранных» элементов. Любимые элементы пользователей в другом представлении таблицы и предпочтительные элементы перечислены в этом представлении таблицы (FavoritesTableView.m).Снимите флажки (непривилегированные) в Избранных Таблица View

По какой-то причине я не могу получить проверенные элементы (избранные элементы), чтобы «снять флажок» из списка FavoritesTableView? Что мне не хватает? Смотрите файл .m ниже ...

FavoritesViewController.h

 #import <UIKit/UIKit.h> 
     #import "StrainTableCell.h" 

     @interface FavoritesViewController : UITableViewController 
     { 

     } 
     @property (strong, nonatomic) NSArray *favoritesArrayset; 
     @property (strong, nonatomic) IBOutlet UITableView *favoritesTable; 
     @property (nonatomic, strong) NSMutableArray * favoritesArray; 

    - (IBAction)backbuttonpressed: (UIBarButtonItem *)sender; 


    @end 

FavoritesViewController.m

- (void)viewWillAppear:(BOOL)animated 
    { 
     [super viewWillAppear:YES]; 

     if (favoritesArray == Nil) 
     { 
      favoritesArray = [[NSMutableArray alloc] init]; 
     } 
     else 
     { 
      [favoritesArray removeAllObjects]; 
     } 

     NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:@"strains"]; 

     if (dataSave != Nil) 
     { 
      favoritesArrayset = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave]; 

      for (NSDictionary *item in favoritesArrayset) 
      { 
       BOOL isChecked = [[item objectForKey:@"checked"] boolValue]; 
       if (isChecked == YES) 
       { 
        [favoritesArray addObject:item]; 
       } 
      } 
     } 

     [favoritesTable reloadData]; 
    } 

    - (void)viewDidLoad 
    { 
     [super viewDidLoad]; 
    } 

    - (void)didReceiveMemoryWarning 
    { 
     [super didReceiveMemoryWarning]; 
    } 

    #pragma mark - Table view data source 
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    { 
     return 1; 
    } 

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     return favoritesArray.count; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     NSArray *Strains = [favoritesArray copy]; 
     NSArray *dataArray = [favoritesArray copy]; 

     static NSString *strainTableIdentifier = @"StrainTableCell"; 

     StrainTableCell *cell = (StrainTableCell *)[tableView dequeueReusableCellWithIdentifier:strainTableIdentifier]; 

     if (cell == nil) 
     { 
      cell = [[StrainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strainTableIdentifier] ; 
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
      cell.selectionStyle = UITableViewCellSelectionStyleBlue; 

      NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StrainTableCell" owner:self options:nil]; 
      cell = [nib objectAtIndex:0]; 

      cell.titleLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:@"Title"]; 
      cell.descriptionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:@"Description"]; 
      cell.ratingLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:@"Rating"]; 
      cell.ailmentLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:@"Ailment"]; 
      cell.actionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:@"Action"]; 
      cell.ingestLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:@"Ingestion"]; 

      cell.whatCellamI = [NSNumber numberWithInt:indexPath.row]; 

      NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row]; 

      cell.textLabel.text = [item objectForKey:@"text"]; 

      [item setObject:cell forKey:@"StrainTableCell"]; 
     } 

     BOOL checked = [[item objectForKey:@"checked"] boolValue]; 

     UIImage *image = (checked) ? [UIImage imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"]; 

     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 

     CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height); 

     button.frame = frame; 
     [button setBackgroundImage:image forState:UIControlStateNormal]; 
     [button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside]; 
     button.backgroundColor = [UIColor clearColor]; 

     cell.accessoryView = button; 

     return cell; 
    } 

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     StrainDetailViewController *detailViewController = [[StrainDetailViewController alloc] 
                  initWithNibName:@"StrainDetailViewController" bundle:nil]; 
     detailViewController.title = [[favoritesArray objectAtIndex:indexPath.row] objectForKey:@"Title"]; 
     detailViewController.strainDetail = [favoritesArray objectAtIndex:indexPath.row]; 
     [self.navigationController pushViewController:detailViewController animated:YES]; 
    } 

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     return 82; 
    } 

    - (IBAction)backbuttonpressed:(id)sender 
    { 
     [self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil]; 
    } 

- (void)checkButtonTapped:(id)sender event:(id)event 
{ 

    NSLog(@"made it here and event is %@",event); 

    NSSet *touches = [event allTouches]; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:self.favoritesTable]; 
    NSIndexPath * indexPath ; 
    indexPath = [self.favoritesTable indexPathForRowAtPoint: currentTouchPosition]; 
    NSLog(@"indexpath is below"); 
    NSLog(@"%@",indexPath); 
    if (indexPath != Nil) 
    { 

     NSMutableDictionary *item = [favoritesArray objectAtIndex:indexPath.row]; 
     BOOL isItChecked = [[item objectForKey:@"checked"] boolValue]; 
     /* 
     if (isItChecked == NO) { 
     NSMutableArray *tmpArray = [[NSMutableArray alloc] init]; 
     NSMutableArray *tmpArray2 = [[NSMutableArray alloc] initWithArray:[favoritesArray allObjects]]; 
     NSString *text1 = [item objectForKey:@"Title"]; 
     for (NSDictionary * object in tmpArray2) { 
     NSString *text2 = [object objectForKey:@"Title"]; 
     if (![text1 isEqualToString:text2]) { 
     [tmpArray addObject:object]; 
     } 
     } 
     // [favoritesArray removeAllObjects]; 
     favoritesArray = [tmpArray copy]; 

     } 
     */ 


     NSMutableArray *quickArray = [[NSMutableArray alloc] initWithArray:favoritesArray]; 
     [quickArray replaceObjectAtIndex:indexPath.row withObject:item]; 


     [item setObject:[NSNumber numberWithBool:!isItChecked] forKey:@"checked"]; 
     favoritesArray = [quickArray copy]; 
     // [self.favoritesArray addObject:item]; 
     // NSLog(@"you have added %d items to favorites", self.favoritesArray.count); 
     [favoritesTable reloadData]; 


    } 


    @end 
+0

Dont поместить весь код в ТАК. положить только требуется код. и формат перед тем, как положить сюда. удалить неопределенное пространство, комментарий и протокол. – CRDave

+0

do u хотите поместить код для галочки в выбранный элемент и снять флажок с невыбранного элемента? – Hari1251

ответ

0

Каждый раз, когда -tableView:cellForRowAtIndexPath: пробегов, вы создаете новую кнопку, установите это к желаемым свойствам и ... выбросить его. (Кажется, это будет шутка на этой неделе.) Вы должны использовать существующую кнопку.

1

В вашем .h возьмите один NSMutableDictionary и создайте для него свойство.

В вашем .m синтезируйте его, а в viewdidLoad укажите словарь.

Теперь поместите это ниже код в CellForRowAtIndex

if([idDictonary objectForKey:[NSString stringWithFormat:@"%d",[indexPath row]]]) 
    { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } 

    else 
    { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 

и поместить это ниже код в DidSelectRowAtIndex

UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath]; 

if (thisCell.accessoryType == UITableViewCellAccessoryNone) 
{ 
    thisCell.accessoryType = UITableViewCellAccessoryCheckmark; 
    [idDictonary setValue:[dataArray objectAtIndex:indexPath.row] forKey:[NSString stringWithFormat:@"%d",[indexPath row]]]; 
} 
else 
{ 
    if([idDictonary objectForKey:[NSString stringWithFormat:@"%d",[indexPath row]]]) 
    { 
     [idDictonary removeObjectForKey:[NSString stringWithFormat:@"%d",[indexPath row]]]; 

     thisCell.accessoryType = UITableViewCellAccessoryNone; 
    } 

} 
[myTableView reloadData]; 
NSLog(@"idDictonary = %@",idDictonary); 

я надеюсь, что это воля помогает U Бретани ...

+0

Привет! В настоящее время у меня нет NSDictionary в моем .h файле (см. Отредактированный код выше). Я также вложил файл .h, чтобы вы могли видеть, как он выглядит на данный момент ... –

+0

Редактирование: теперь я теперь получаю кнопку «снимите флажок» (см. Добавленный код в нижней части .m), но «unchecked» изображение не удаляет ячейку из favoritestableview. Мысли? –

+0

u хотите удалить полную ячейку или строку (не отмеченную) из вида таблицы? – Hari1251

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