2014-01-09 2 views
0

Мне удалось показать заголовки в разделах раздела в iOS 7, но текст не отображается в iOS 6. Я понимаю, что вы можете использовать заголовки или пользовательские заголовки, но не оба одновременно, поэтому я убедился не определять tableView:viewForHeaderInSection:.Как показать заголовки разделов таблицы в iOS 6?

enter image description hereenter image description here

Это соответствующий код. Это подкласс UIViewController, а не UITableViewController. Мне нужен липкий заголовок таблицы, поэтому мне пришлось выполнять пользовательскую композицию в виде таблицы.

- (void)loadView 
{ 
    [super loadView]; 

    // "width" and "height" properties are convenience methods 
    // that I defined in a UIView category. 
    self.tableView = [[UITableView alloc] 
     initWithFrame:CGRectMake(
      0.0, 
      SEARCH_BAR_HEIGHT + self.avatarCollectionView.height, 
      self.view.width, 
      self.view.height - (SEARCH_BAR_HEIGHT + self.avatarCollectionView.height) 
     ) 
     style:UITableViewStylePlain 
    ]; 
    [self.view addSubview:self.tableView]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.tableView.delegate = self; 
    self.tableView.dataSource = self; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // displayAlphabet is an NSMutableArray of one character strings. 
    // It is a subset of the entire alphabet. For example, it can be: 
    // @[@"A", @"B", @"C", @"E", @"X", @"Z"] 
    return self.displayAlphabet.count; 
} 

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    return [self.displayAlphabet objectAtIndex:section]; 
} 

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView 
{ 
    return self.displayAlphabet; 
} 

Как получить текст заголовка в iOS 6?

+0

Что такое тип данных элементов для self.displayAlphabet? –

+1

Вы уверены, что вернули ненулевую высоту для 'tableView: heightForHeaderInSection:' или задали свойство 'sectionHeaderHeight' в представлении таблицы? – smileyborg

+0

Как получить алфавит, независимо от того, хранится ли он локально или извлекается из db/some где – codercat

ответ

4

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

Объявление NSArray *titleArray, чтобы держать ваши заголовки. В viewDidLoad инициализируйте таблицу, а также ваш массив заголовков.

tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain]; 
tableView.delegate   = self; 
tableView.dataSource  = self; 
tableView.backgroundColor = [UIColor whiteColor]; 
tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); 
[self.view addSubview:tableView]; 

titleArray = @[@"A", @"B", @"C", @"E", @"X", @"Z"];

Теперь, несколько метод делегата, как,

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 3; 
} 

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    return [titleArray objectAtIndex:section]; 
} 

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView 
{ 
    return titleArray; 
} 

А вот выход.

iOS6:

iOS6 Screen Shot

ioS7:

ios7 screen Shot

Я надеюсь, что помогает.

0

Класс UILocalizedIndexedCollation является удобством для организации, сортировки и локализации данных для табличного представления с индексом раздела. Затем в источнике данных таблицы используется объект сопоставления, чтобы обеспечить представление таблицы со входом для заголовков разделов и заголовков разделов.

Apple, Sample App

SimpleIndexedTableView

Referance Doc: Apple Inc

enter image description here

enter image description here

@property (nonatomic) NSMutableArray *sectionsArray; 
@property (nonatomic) UILocalizedIndexedCollation *collation; 

-(void)viewDidLoad{ 

[self configureSections]; 
[self.tableView reloadData]; 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    // The number of sections is the same as the number of titles in the collation. 
    return [[self.collation sectionTitles] count]; 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Check to see whether the normal table or search results table is being displayed and return the count from the appropriate array 

    NSArray *timeZonesInSection = (self.sectionsArray)[section]; 

    NSLog(@"count tableview %d",timeZonesInSection.count); 

    return [timeZonesInSection count]; 

} 

/* 
Section-related methods: Retrieve the section titles and section index titles from the collation. 
*/ 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    return [self.collation sectionTitles][section]; 
} 


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 
    return [self.collation sectionIndexTitles]; 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 
    return [self.collation sectionForSectionIndexTitleAtIndex:index]; 
} 


- (void)configureSections { 


    // Get the current collation and keep a reference to it. 
    self.collation = [UILocalizedIndexedCollation currentCollation]; 

    NSInteger index, sectionTitlesCount = [[self.collation sectionTitles] count]; 

    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount]; 

    // Set up the sections array: elements are mutable arrays that will contain the time zones for that section. 
    for (index = 0; index < sectionTitlesCount; index++) { 
     NSMutableArray *array = [[NSMutableArray alloc] init]; 
     [newSectionsArray addObject:array]; 
    } 


    self.sectionsArray = newSectionsArray; 
} 
0

Используйте следующий код класса UITableView, где вы хотите, чтобы показать данные -:

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

{ 
NSString *title = nil; 
switch (section) 
{ 
    case section1: 
     title= @"First"; 
     break; 
    case section2: 
     title= @"Second"; 
     break; 
    case section3: 
     title = @"Third"; 
     break; 
    default: 
     break; 
} 

return title; 

}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 

{

// CGRect screenRect = [[UIScreen mainScreen] applicationFrame]; 
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0,100, 320, 44.0)]; 
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(15.0, -28.0, 300.0, 90.0)]; 
headerLabel.backgroundColor = [UIColor clearColor]; 
headerLabel.opaque = NO; 
headerLabel.font = [UIFont boldSystemFontOfSize:15]; 
headerLabel.textColor = [UIColor whiteColor]; 
    //headerView.contentMode = UIViewContentModeScaleToFill; 

    // Add the label 
    switch (section) 
    { 
     case section1: 
     {     
      headerLabel.text = @"First"; 

      [headerView addSubview: headerLabel]; 
      break; 
     } 
     case section2: 
     {     
      headerLabel.text = @"Second"; 

      [headerView addSubview: headerLabel]; 
      break; 
     } 

     case section3: 
     { 
      headerLabel.text = @"Third"; 

      [headerView addSubview: headerLabel]; 
      break; 
     } 


     default: 
      break; 
    } 


    // Return the headerView 

возврата headerView ;; }

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