Как реализовать разделы в табличном представлении, содержащие базу данных SQLite? - PullRequest
0 голосов
/ 25 марта 2012

Итак, у меня есть UITableView, большой объем данных, который отображается с множеством строк, и я хочу сделать разделы (например, приложение контактов по умолчанию и его разделы).Итак, мой код (файл listViewController.m):

#import "FailedBanksListViewController.h"
#import "FailedBankDatabase.h"
#import "FailedBankInfo.h"
#import "FailedBanksDetailViewController.h"
#import "BIDAppDelegate.h"

@implementation FailedBanksListViewController
@synthesize failedBankInfos = _failedBankInfos;
@synthesize details = _details;


- (void)viewDidLoad {

    self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"3.png"]];;
    [super viewDidLoad];
    self.failedBankInfos = [FailedBankDatabase database].failedBankInfos;
    self.title = @"Продукты";
}

- (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;
    self.failedBankInfos = nil;
    self.details = nil;

}
- (void) viewWillAppear:(BOOL)animated
{


}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return [_failedBankInfos count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_failedBankInfos count];
}


// 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];
    }


    // Set up the cell...
    FailedBankInfo *info = [_failedBankInfos objectAtIndex:indexPath.row];
    cell.textLabel.text = info.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@", info.city, info.state];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.details == nil) {
        self.details = [[FailedBanksDetailViewController alloc] initWithNibName:@"FailedBanksDetailViewController" bundle:nil];        
    }
    FailedBankInfo *info = [_failedBankInfos objectAtIndex:indexPath.row];
    _details.uniqueId = info.uniqueId;
    [self.navigationController pushViewController:_details animated:YES];
}

- (void)dealloc {
    self.failedBankInfos = nil;
}


@end

1 Ответ

0 голосов
/ 25 марта 2012

С вашим кодом у вас должно быть несколько разделов (каждый из которых точно равен другим).Идея представления таблицы с несколькими разделами состоит в том, чтобы (обычно) иметь двумерный массив (а не одномерный, как в вашем случае).Тогда каждая строка будет представлять раздел для вашего табличного представления.

Например, если у вас есть массив, структурированный таким образом (и я знаю, что вы не можете инициализировать его таким образом):

arr = {
  {'apple','orange','banana'},
  {'CD-Rom', 'DVD', 'BR-Disk'},
  {'AK-47', 'Rocket launcher', 'Water gun'}
}

Ваш метод количества разделов может вернуть [arr count], а количество строк в разделе s может вернуть [[arr objectAtIndex:s] count].И помните, что вы можете установить заголовок для каждого раздела с помощью метода источника данных табличного представления tableView:titleForHeaderInSection:.

Если вы хотите загрузить информацию из БД SQLite, ничего не может измениться.Это точно так же, но вам придется придерживаться способа получения ваших данных.

Когда вы поймете, что понимаете все эти вещи, тогда ознакомьтесь с Базовой платформой данных .

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