Я не знаю, почему мой Tableview не выдвигал DetailView при выборе строки - PullRequest
0 голосов
/ 21 июля 2011

Я нашел этот пример кода и изменил код, чтобы он делал то, что я хочу.Данные таблицы загружаются из plist, он работает, данные отображаются в секциях, он работает теперь, когда выбрана строка, я хочу нажать на контроллер Detailview, чтобы показать больше деталей.Grrrr, это не работает, и я не знаю почему.Разница между этим кодом и другим, где он работает нормально, заключается в том, что ICB_SectionedTableViewDemoViewController объявлен как класс в appDelegate, и я не знаю, является ли это частотой, когда я хочу выдвинуть DetailViewController.

вот код моего rootController с именем ICB_SectionedTableViewDemoViewController.m

//  ICB_SectionedTableViewDemoViewController.m
//  ICB_SectionedTableViewDemo
//
//  Created by Matt Tuzzolo on 12/10/10.
//  Copyright 2010 ELC Technologies. All rights reserved.
//

#import "ICB_SectionedTableViewDemoViewController.h"
#import "ICB_SectionedTableViewDemoAppDelegate.h"
#import "DetailViewController.h"



@implementation ICB_SectionedTableViewDemoViewController

@synthesize books, sections ;

- (void)viewDidLoad {

    self.books = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"books" ofType:@"plist"]];
    self.sections = [[NSMutableDictionary alloc] init];

    BOOL found;

    // Loop through the books and create our keys
    for (NSDictionary *book in self.books)
    {        
        NSString *c = [[book objectForKey:@"author"] substringToIndex:1];

        found = NO;

        for (NSString *str in [self.sections allKeys])
        {
            if ([str isEqualToString:c])
            {
                found = YES;
            }
        }

        if (!found)
        {     
            [self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
        }
    }

    // Loop again and sort the books into their respective keys
    for (NSDictionary *book in self.books)
    {
        [[self.sections objectForKey:[[book objectForKey:@"author"] substringToIndex:1]] addObject:book];
    }    

    // Sort each section array
    for (NSString *key in [self.sections allKeys])
    {
        [[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"author" ascending:YES]]];
    }    

    [super viewDidLoad];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return [[self.sections allKeys] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{    
    if(section == 0)
        return @"COULEURS";
    else
        return @"MOTIFS";    

  //  return [[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    NSDictionary *book = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];

    cell.textLabel.text = [book objectForKey:@"title"];    
    cell.detailTextLabel.text = [book objectForKey:@"description"];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {



    //Initialize the detail view controller and display it.
    DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];
    dvController.CL = [self.books objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:dvController animated:YES];
 //   [self presentModalViewController:dvController animated:YES];
 //   [self.view addSubview:dvController.view];
    [dvController release];



}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


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

@end

спасибо за вашу очень полезную помощь и напомните, что я новичок, и мой первый язык - Franch.

Ответы [ 2 ]

0 голосов
/ 21 июля 2011

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

0 голосов
/ 21 июля 2011

После просмотра проекта кажется, что вы не создали UINavigationController.Итак, я предлагаю вам использовать этот код для application:didFinishLaunchingWithOptions::

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    UINavigationController* navigation = [[UINavigationController alloc] init];
    [navigation pushViewController:viewController animated:NO];
    [window addSubview:navigation.view];

    [self.window makeKeyAndVisible];

    return YES;
 }

Здесь создается экземпляр UINavigationController и на него помещается ваш первый (корневой) контроллер.

Важно : ваше приложение имеет больше проблем, поэтому оно не будет работать, но по крайней мере ваш контроллер DetailView будет загружен и попытается отобразить его.О найденных проблемах:

  1. в didSelectRowAtIndexPath вы используете неправильное имя пера;

  2. в DetailViewController viewDidLoad вы используете свойство CL.title, которое не определено;

после устранения этих проблем может появиться подробный вид.

СТАРЫЙ ОТВЕТ:

Установите точку останова в tableView:didSelectRowAtIndexPath: и убедитесь, что ваш DetailViewController создан правильно, а также что self.navigationController не ноль.

В качестве альтернативы вы можете добавить трассировки NSLog в свой код (этоважная техника отладки):

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //Initialize the detail view controller and display it.
    DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];
    dvController.CL = [self.books objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:dvController animated:YES];

    NSLog(@"navController: %@", [self.navigationController description]);
    NSLog(@"dvController.CL: %@", [dvController.CL description]);


 //   [self presentModalViewController:dvController animated:YES];
 //   [self.view addSubview:dvController.view];
   [dvController release];

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...