iPhone TableView Данные в 2 раздела - PullRequest
0 голосов
/ 18 марта 2011

Я пытаюсь получить представление таблицы, чтобы разбить данные в массиве на разделы ...

Я довольно новичок в этом, но ниже приведен мой фрагмент кода

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{

    if(section == 0) 
    {
        contentArray = [[NSArray arrayWithObjects:@"Send SMS", @"Reports", nil] retain];
    }
    if(section == 1) 
    {
        contentArray = [[NSArray arrayWithObjects:@"Accounts", nil] retain];
    }

    return [contentArray count];
}

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

Может ли кто-нибудь помочь ...

Спасибо

Ответы [ 4 ]

2 голосов
/ 18 марта 2011

Перво-наперво, у вас есть утечка в коде, который вы представили.Удалите два вызова на retain.

Во-вторых, у вас классическая проблема - иметь несколько цепочек switch / if..else, основанных на одной и той же информации.Это кричит для решения OO.

Сначала создайте класс TableSection:

@interface TableSection : NSObject
{ }
@property (nonatomic, copy) NSString* header;
@property (nonatomic, copy) NSArray* rows;

- (NSInteger)numberOfRows;
- (UITableViewCell*)cellInTableView: (UITableView*)tableView forRow: (NSInteger)row;

@end

@implementation TableSection
@synthesize header;
@synthesize rows;
- (void)dealloc {
    [header release];
    [rows release];
    [super dealloc];
}

- (NSInteger)numberOfRows {
    return rows.count;
}

- (UITableViewCell*)cellInTableView: (UITableView*)tableView forRow: (NSInteger)row {
    // create/reuse, setup and return a UITableViewCell
}

@end

Теперь в вашем TableViewController

@interface MyViewController : UITableViewController
{ }
@property (nonatomic, retain) NSArray* tableSections;

@end

@implementation MyViewController
- (void)dealloc {
    [tableSections release];
    [super dealloc];
}

- (void)viewDidLoad {
    TableSection* section1 = [[TableSection alloc] init];
    [section1 setRows: [NSArray arrayWithObjects: @"Send SMS", @"Reports", nil]];
    TableSectlion* section2 = [[TableSection alloc] init];
    [section2 setRows: [NSArray arrayWithObjects: @"Accounts", nil]];
    [self setTableSections: [NSArray arrayWithObjects: section1, section2, nil]];
    [section2 release];
    [section1 release];
}

- (void)viewDidUnload {
    [self setTableSections: nil];
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView: (UITableView*)tableView {
    return self.tableSections.count;
}

- (NSInteger)tableView: (UITableView*)tableView numberOfRowsInSection: (NSInteger)section {
    return [[self.tableSections objectAtIndex: section] numberOfRows];
}


- (UITableViewCell*)tableView: (UITableView*)tableView cellForRowAtIndexPath: (NSIndexPath*)indexPath {
    return [[self.tableSections objectAtIndex: indexPath.section] cellInTableView: tableView forRow: indexPath.row];
}

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

@end
1 голос
/ 18 марта 2011

не переключайте (и не допускайте утечки) ваши данные контента в одном из источников данных tableview или методов делегата. tableView:numberOfRowsInSection: можно вызывать произвольное количество раз. С вашим кодом вы полагаетесь на определенный порядок, в котором эти методы вызываются.

У вас должен быть отдельный массив для каждого раздела (или один массив, содержащий два массива разделов)

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if(section == 0) {
        return [section0Array count];
    }
    if(section == 1) {
        return [section1Array count];
    }
    return 0;

}

И вы можете создать эти массивы в viewDidLoad:

section0Array = [[NSArray arrayWithObjects:@"Send SMS", @"Reports", nil] retain];
section1Array = [[NSArray arrayWithObjects:@"Accounts", nil] retain];
0 голосов
/ 11 октября 2012

Полагаю, вы должны поместить код в cellForRowAtIndexPath, потому что там, где вы пишете, мы обычно добавляем количество строк в каждом разделе

0 голосов
/ 18 марта 2011

Необходимо убедиться, что метод (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath также возвращает правильные ячейки на основе вашего разбиения массива содержимого. Вы можете сделать аналогичную проверку в методе что-то вроде

switch(indexPath.section) 
{ 
     case 0:  //First Section 
     switch(indexPath.row) 
     {
         case 0: //Setup the cell Send SMS
             break;
         case 1: //Setup the cell Reports
             break;
     }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...