2012-04-14 3 views
1

Я пытаюсь узнать, как закодировать UITableView и имеет некоторые проблемы с программированием раздела.Различные заголовки разделов в UITableView вложенного NSArray

Я объявил 3 массива со строками и 1 массив с 3 массивами.

firstSection = [NSArray arrayWithObjects:@"Red", @"Blue", nil]; 
secondSection = [NSArray arrayWithObjects:@"Orange", @"Green", @"Purple", nil]; 
thirdSection = [NSArray arrayWithObject:@"Yellow"]; 

array = [[NSMutableArray alloc] initWithObjects:firstSection, secondSection, thirdSection, nil]; 

Чтобы показывает заголовки

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

NSString * title; 
title = [NSString stringWithFormat:@"%@" , [array objectAtIndex:section]]; 

return title; 
} 

, который показывает, следовательно, массив в качестве заголовков

enter image description here

можно ли на самом деле показать имя секций с именами таких массивов, как firstSection и secondSection?

+0

Я действительно не понимаю, что вы хотите здесь - имя массива, например «firstSection»? Или элемент из массива, например, «Красный»? – SomaMan

+0

Да, я хочу показать имена массивов. – wakaka

ответ

5

В вашем случае, это лучше хранить массивы в NSDictionary. Например, если вы объявляете и синтезировать NSDictionary переменную tableContents и NSArray под названием titleOfSections, вы можете сделать что-то вроде этого:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    //These will automatically be released. You won't be needing them anymore (You'll be accessing your data through the NSDictionary variable) 
    NSArray *firstSection = [NSArray arrayWithObjects:@"Red", @"Blue", nil]; 
    NSArray *secondSection = [NSArray arrayWithObjects:@"Orange", @"Green", @"Purple", nil]; 
    NSArray *thirdSection = [NSArray arrayWithObject:@"Yellow"]; 

    //These are the names that will appear in the section header 
    self.titleOfSections = [NSArray arrayWithObjects:@"Name of your first section",@"Name of your second section",@"Name of your third section", nil]; 

    NSDictionary *temporaryDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:firstSection,@"0",secondSection,@"1",thirdSection,@"2",nil]; 
    self.tableContents = temporaryDictionary; 
    [temporaryDictionary release]; 
} 

Тогда в методах контроллера просмотра таблицы:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
    return [self.titleOfSections count]; 
} 
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { 
    return [[self.tableContents objectForKey:[NSString stringWithFormat:@"%d",section]] count]; 
} 
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    //Setting the name of your section 
    return [self.titleOfSections objectAtIndex:section]; 
} 

Тогда доступ к содержимому каждого массива в вашем cellForRowAtIndexPath методе:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; 

    NSArray *arrayForCurrentSection = [self.tableContents objectForKey:[NSString stringWithFormat:@"%d",indexPath.section]]; 

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] 
       initWithStyle:UITableViewCellStyleSubtitle 
       reuseIdentifier:SimpleTableIdentifier] autorelease]; 
    } 
    cell.textLabel.text = [arrayForCurrentSection objectAtIndex:indexPath.row]; 

    return cell; 
} 
+0

Спасибо за ответ. Я вижу, что вы создали третий массив, называемый titleOfSections, и поместили в него имена. Можно ли показать имена массива без этого? – wakaka

+0

@wakaka не то, что я знаю. – sooper

+0

Ну, я думаю, это единственный способ. Спасибо – wakaka

0

может у сделать как этот

NSArray *SectionArray = [[NSArray alloc]initwithArray:[array objectAtIndex:section]]; 

    NSString * title; 

    title = [NSString stringWithFormat:@"%@" , [SectionArray objectAtIndex:section]]; 

    return title; 
+1

Это не будет работать, так как у thirdSection есть только 1 элемент, поэтому в случае раздела = 2 индекс будет вне диапазона. Я не уверен, что вакака действительно ясно дал понять, что он хочет ... – SomaMan

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