UITableView (без использования шаблона навигации) получение конкретных данных из plist - PullRequest
3 голосов
/ 01 декабря 2010

Я использую пример на странице 210 книги «Начало разработки iPhone (изучение iPhone SDK)», и это похоже на то, что я хочу сделать, но этот конкретный пример усложняется использованием разделов в TableView. У меня есть определенная иерархия в моем списке ...

Root  ---- Dictionary
        Rows  ---- Array
                Item 0- Dictionary
                        fullName  ---- String
                        address   ---- String
                Item 1   ---- Dictionary
                        fullName  ---- String
                        address   ---- String

Итак, у меня есть UITableView, который занимает небольшую часть представления на этом "экране". Остальная часть представления имеет другие элементы, поэтому я выбрал орех, чтобы использовать шаблон навигации.

Код, который я использую, не совпадает, потому что мне не совсем понятно, какие поля вызывать.

Может кто-нибудь показать мне ОЧЕНЬ простой пример того, как я мог бы перечислить все «firstNames» в этой таблице. Если что-то не так с моим списком, пожалуйста, дайте мне знать, что конкретно изменить.

В двух словах, я хочу просмотреть все словари Item # и перечислить все имена. Мой дизайн похож на список контактов, но не совсем список контактов.

Прямо сейчас я использую этот код, который просто отображает слово «Rows». Я изменил слова строк на Rows1 в моем списке, и он появляется, поэтому он захватывает этот «элемент массива». Надеюсь, я сказал это правильно.

-(void)viewDidLoad {    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];

    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.names = dict;
    [dict release];

    NSArray *array = [[names allKeys] sortedArrayUsingSelector:@selector(compare:)];
    self.listData = array;

    [super viewDidLoad];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *SimpleTableIdentifier = @"Identifier";

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

    NSUInteger row = [indexPath row];
    cell.textLabel.text = [listData objectAtIndex:row];
    return cell;
}

Я искал в Интернете несколько дней, пытаясь найти простой пример, использующий иерархию списков для отображения элементов в таблице, которая не является частью шаблона навигации.

Большое спасибо

1 Ответ

2 голосов
/ 01 декабря 2010

Я написал пример кода , это адресная книга.Он считывает данные из списка.

список:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>name</key>
        <string>Vikingo</string>
        <key>familyname</key>
        <string>Segundo</string>
        <key>street</key>
        <string>Avenida Roca y Coranado</string>
        <key>number</key>
        <integer>20</integer>
        <key>city</key>
        <string>Santa Cruz de la Sierra</string>
        <key>province</key>
        <string>Santa Cruz</string>
        <key>country</key>
        <string>Bolivia</string>
        <key>pictureurl</key>
        <string>vikingosegundo.png</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Santa</string>
        <key>familyname</key>
        <string>Claus</string>
        <key>street</key>
        <string>Avenida Roca y Coranado</string>
        <key>number</key>
        <integer>20</integer>
        <key>city</key>
        <string>Santa Cruz de la Sierra</string>
        <key>province</key>
        <string>Santa Cruz</string>
        <key>country</key>
        <string>Finland</string>
        <key>pictureurl</key>
        <string>robot-santa.png</string>
    </dict>
</array>
</plist>

читает список:

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"contacts" ofType:@"plist"];
contacts = [[NSArray arrayWithContentsOfFile:plistPath] retain];

отображать контакты в виде таблицы:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [contacts 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:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    NSDictionary *dict = [contacts objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [dict objectForKey:@"name"], [dict objectForKey:@"familyname"]];

    return cell;
}

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


    DetailContactViewController *detailViewController = [[DetailContactViewController alloc] initWithNibName:@"DetailContactView" bundle:nil];
    detailViewController.contact = [contacts objectAtIndex:indexPath.row];
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];

    [detailViewController release];

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