Какой код мне нужно написать в методе didSelectRowAtIndexPath для перехода / перехода к новому ViewController, в соответствии с моим примером? - PullRequest
0 голосов
/ 30 мая 2018

Я ссылаюсь на проект из GitHub.

Я пытаюсь изменить его в соответствии с моим требованием, но я не понимаю и не могу понять, какой код я должен написать в методе didSelectRowAtIndexPath.

Here is image

Что мне нужно, так это то, что после щелчка строки tableView он может достигнуть уровня 0 или уровня 1 (here level 0 means - row has no sub child and level 1 means row has subview/child rows )

Когда я щелкаю по любой строке tableView любого уровня 0или уровень 1, он должен перейти к следующему viewController.

В этом примере строки с номерами 2 и 3 являются расширяемыми, т.е. он содержит строки уровня 1, строки 0, 1, 4 и 5 - строки уровня 1, которые они надеваютне расширяйте.

Вот ссылка на проект (обновленная ссылка на проект)

***** Добавлен код ****

кодЯ написал в классе AppDelegate,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.


   userDefaults=[NSUserDefaults standardUserDefaults];
mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];


if ([[NSUserDefaults standardUserDefaults] boolForKey:@"loginSuccess"]) {
      NSLog(@"Login Done!!!");

      HomeViewController *homeVC=[mainStoryboard instantiateViewControllerWithIdentifier:@"homeId"];

      SampleNavigationController *navigation = [[SampleNavigationController alloc] initWithRootViewController:homeVC];

    //SWRevealViewController * vc= [[SWRevealViewController alloc]init];

    //ExpandableTableViewController *sidemenu = (ExpandableTableViewController*)[mainStoryboard instantiateViewControllerWithIdentifier:@"sideMenu"];

      self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
      self.window.rootViewController = navigation;
      [self.window makeKeyAndVisible];

  }else
   {

      LoginViewController *loginVC=[mainStoryboard instantiateViewControllerWithIdentifier:@"LoginId"];

      self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
      self.window.rootViewController = loginVC;
      [self.window makeKeyAndVisible]; 
}

 return YES;

}

А в классе LoginViewController я написал код

- (IBAction)loginButtonMethod:(id)sender {
    [self->userdefaults setBool:YES forKey:@"loginSuccess"];

    InboxView *inboxVC=[self.storyboard  instantiateViewControllerWithIdentifier:@"id1"];
    [self.navigationController pushViewController:inboxVC animated:YES];
    [[self navigationController] setNavigationBarHidden:NO];
}

Ответы [ 3 ]

0 голосов
/ 30 мая 2018

Пожалуйста, напишите ваш родительский навигационный код следующим способом.Для дочернего вида

- (void)ftFoldingTableView:(FTFoldingTableView *)ftTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath--->%ld",(long)indexPath.row);
    //Write your  push next view controller code 
    [ftTableView deselectRowAtIndexPath:indexPath animated:YES];
}

Введите код навигации родительского вида, используя следующий метод

- (void)ftFoldingTableView:(FTFoldingTableView *)ftTableView willChangeToSectionState:(FTFoldingSectionState)sectionState section:(NSInteger)section
{
    NSLog(@"section-->%ld",(long)section);
// Write push level 0 or parent view move next view controller code 

   // NSLog(@"section: %ld is about to %@", section, sectionState == FTFoldingSectionStateFold ? @"close" : @"open");
}
0 голосов
/ 31 мая 2018

Попробуйте этот код работает правильно

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //check if the row at indexPath is a child of an expanded parent.
    //At a time only one parent would be in expanded state
    NSInteger indexSelected = indexPath.row;
    NSDictionary *dicSelected  =[self.itemsInTable objectAtIndex:indexSelected];
    /**
     Resolved the issue of top line separator dissapearing upon selecting a row (hackishly) by reloading the selected cell
     */
    @try {
        [self.menuTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    @catch (NSException *exception) {
    }

    [tableView setSectionIndexBackgroundColor:[UIColor blackColor]];
    //
    //Collapse any other expanded cell by iterating through the table cells.
    //Don't collapse if the selected cell is a child of an expanded row.
    NSDictionary *dicCellToCollapse  =[self.itemsInTable objectAtIndex:g_ExpandedCellIndex];
    NSInteger numRowsCollapsed = 0;
    NSInteger level = [[dicSelected valueForKey:@"level"] integerValue];

    if(level==0 && [dicCellToCollapse valueForKey:@"SubItems"] && (g_ExpandedCellIndex != indexPath.row))
    {
        NSArray *arr=[dicCellToCollapse valueForKey:@"SubItems"];
        BOOL isTableExpanded=NO;

        for(NSDictionary *subitems in arr )
        {
            NSInteger index=[self.itemsInTable indexOfObjectIdenticalTo:subitems];
            isTableExpanded=(index>0 && index!=NSIntegerMax);
            if(isTableExpanded) break;
        }
        //
        //Collapse the parent cell if its expanded
        if(isTableExpanded)
        {
            [self CollapseRows:arr];
            numRowsCollapsed = [arr count]-1;
        }
    }

    //
    //go about the task of expanding the cell if it has subitems
    NSDictionary *dic;
    if (g_ExpandedCellIndex < indexPath.row && numRowsCollapsed)
    {
        dic = [self.itemsInTable objectAtIndex:indexPath.row-numRowsCollapsed-1];
    }
    else
    {
        dic = [self.itemsInTable objectAtIndex:indexPath.row];

    }



    //
    //Check if the selected cell has SubItems i.e its a Parent cell
    if([dic valueForKey:@"SubItems"])
    {
        arr=[dic valueForKey:@"SubItems"];
        BOOL isTableExpanded=NO;

        for(NSDictionary *subitems in arr )
        {
            NSInteger index=[self.itemsInTable indexOfObjectIdenticalTo:subitems];
            isTableExpanded=(index>0 && index!=NSIntegerMax);
            if(isTableExpanded) break;
        }
        //
        //Collapse the parent cell if its expanded
        if(isTableExpanded)
        {
            [self CollapseRows:arr];
        }
        //
        //Else expand the cell to show SubItems
        else
        {
//                    ViewController3 * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"id3"];
//                    [self.navigationController pushViewController:vc animated:YES];
            //
            //store the location of the cell that is expanded
            NSUInteger rowIndex;
            if (g_ExpandedCellIndex < indexPath.row && numRowsCollapsed)
            {
                rowIndex = indexPath.row-numRowsCollapsed;//zero based index
                g_ExpandedCellIndex = indexPath.row-numRowsCollapsed-1;//zero based index
            }
            else
            {
                rowIndex = indexPath.row+1;
                g_ExpandedCellIndex = indexPath.row;
            }
            //
            //Insert the SubItems

            NSMutableArray *arrCells=[NSMutableArray array];
            for(NSDictionary *dInner in arr )
            {
                [arrCells addObject:[NSIndexPath indexPathForRow:rowIndex inSection:0]];
                [self.itemsInTable insertObject:dInner atIndex:rowIndex++];

                ViewController3 * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"id3"];
                [self.navigationController pushViewController:vc animated:YES];
            }
            [self.menuTableView insertRowsAtIndexPaths:arrCells withRowAnimation:UITableViewRowAnimationTop];


        }
    }
    //Else a subItem has been clicked. We need to push the relevant view into segue
    else
    {
          NSString* strId =[dic valueForKey:@"id"];
          NSDictionary *dict = arr[0];
          NSString *id1=[dict objectForKey:@"id"];

          NSLog(@"%@",strId);
          NSLog(@"%@",id1);

          if([id1 isEqualToString:@"sme_marketwatch"])
          {
                      ViewController3 * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"id3"];
                      [self.navigationController pushViewController:vc animated:YES];
          }

        ViewController3 * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"id3"];
        [self.navigationController pushViewController:vc animated:YES];
//
//        ViewController1 * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"id1"];
//        [self.navigationController pushViewController:vc animated:YES];


//          NSString* strId =[dic valueForKey:@"id"];
//          NSLog(@"Id is %@",strId);
//
//         if([strId isEqualToString:@"getquote"]) //getquote
//         {
//             ViewController3 * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"id3"];
//             [self.navigationController pushViewController:vc animated:YES];
//         }



    }
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ViewController3 *newView = [storyboard instantiateViewControllerWithIdentifier:@"id3"];
    [self presentViewController:newView animated:YES completion:nil];




//    ViewController3 * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"id3"];
//      [self.navigationController pushViewController:vc animated:YES];

}
0 голосов
/ 30 мая 2018

Попробуйте это.ProductVC - это ваш класс, в который вы хотите нажать

NSString * storyboardName = @"Main";
        NSString * viewControllerID = @"id3";
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
        ViewController3 * controller = (ViewController3 *)[storyboard instantiateViewControllerWithIdentifier:viewControllerID];

        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: controller];
        [navController setViewControllers: @[controller] animated: YES];
        [self.revealViewController setFrontViewController:navController];
        [self.revealViewController setFrontViewPosition: FrontViewPositionLeft animated: YES];

Таким образом, вы можете перейти к любому классу, в didselectrowatindexpath просто добавьте проверку, для какой строки вы хотите, чтобы какой класс выдвинул.

...