UITableView - Сгруппированная таблица. iOS (Cocoa Touch), Objective-C - PullRequest
1 голос
/ 29 сентября 2011

Я нашел учебник для представления UITableView - детализация таблицы, исходный код , но я бы хотел добавить небольшое обновление.Моя цель - добавить сгруппированное табличное представление с двумя разделами на уровне 0 (CurrentLevel == 0).Итак, я начал с:

  1. Изменить стиль табличного представления (в RootViewController.xib) с простого на сгруппированный.(Работает нормально).

  2. Изменения на RootViewController.m:

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

до

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(CurrentLevel == 0)    
    return 2;
else
    return 1;
Добавить новый ключ в data.plist с именем: Other.

После этого CurrentLevel 0 возвращает 2 раздела с одинаковыми данными для objectForKey: @ "Rows".Я не знаю, как изменить

-(void)viewDidLoad, 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section,
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

методы для загрузки данных из data.plist для моего нового ключа @ «Другое», где ключ @ «Другое» означает 2-й раздел таблицы в таблице CurrentLevel 0view.

Это исходный код для:

DrillDownAppAppDelegate.h

//
//  DrillDownAppAppDelegate.h
//  DrillDownApp
//
//  Created by iPhone SDK Articles on 3/8/09.
//  Copyright www.iPhoneSDKArticles.com 2009. 
//

#import <UIKit/UIKit.h>

@interface DrillDownAppAppDelegate : NSObject <UIApplicationDelegate> {

    UIWindow *window;
    UINavigationController *navigationController;

    NSDictionary *data;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) NSDictionary *data;

@end

DrillDownAppAppDelegate.m

//
//  DrillDownAppAppDelegate.m
//  DrillDownApp
//
//  Created by iPhone SDK Articles on 3/8/09.
//  Copyright www.iPhoneSDKArticles.com 2009. 
//

#import "DrillDownAppAppDelegate.h"
#import "RootViewController.h"


@implementation DrillDownAppAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize data;


- (void)applicationDidFinishLaunching:(UIApplication *)application {

    NSString *Path = [[NSBundle mainBundle] bundlePath];
    NSString *DataPath = [Path stringByAppendingPathComponent:@"data.plist"];

    NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
    self.data = tempDict;
    [tempDict release];

    // Configure and show the window
    [window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}


- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}  


- (void)dealloc {
    [data release];
    [navigationController release];
    [window release];
    [super dealloc];
}

@end

RootViewController.h

//
//  RootViewController.h
//  DrillDownApp
//
//  Created by iPhone SDK Articles on 3/8/09.
//  Copyright www.iPhoneSDKArticles.com 2009. 
//

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {

NSArray *tableDataSource;
NSString *CurrentTitle;
NSInteger CurrentLevel;
}

@property (nonatomic, retain) NSArray *tableDataSource;
@property (nonatomic, retain) NSString *CurrentTitle;
@property (nonatomic, readwrite) NSInteger CurrentLevel;

@end

RootViewController.m

//
//  RootViewController.m
//  DrillDownApp
//
//  Created by iPhone SDK Articles on 3/8/09.
//  Copyright www.iPhoneSDKArticles.com 2009. 
//

#import "RootViewController.h"
#import "DrillDownAppAppDelegate.h"
#import "DetailViewController.h"

@implementation RootViewController

@synthesize tableDataSource, CurrentTitle, CurrentLevel;


- (void)viewDidLoad {
    [super viewDidLoad];

    if(CurrentLevel == 0) {

        //Initialize our table data source
        NSArray *tempArray = [[NSArray alloc] init];
        self.tableDataSource = tempArray;
        [tempArray release];

        DrillDownAppAppDelegate *AppDelegate = (DrillDownAppAppDelegate *)[[UIApplication sharedApplication] delegate];
        self.tableDataSource = [AppDelegate.data objectForKey:@"Rows"];

        self.navigationItem.title = @"Zvolte trasu";
    }
    else 
        self.navigationItem.title = CurrentTitle;   
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(CurrentLevel == 0)    
        return 2;
    else
        return 1;
}


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

    // Set up the cell...


    NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
    cell.textLabel.text = [dictionary objectForKey:@"Title"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    UIImage *rowImage = [UIImage imageNamed:[dictionary objectForKey:@"Image"]];
    cell.imageView.image = rowImage;

    return cell;
}


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

    //Get the dictionary of the selected data source.
    NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row];

    //Get the children of the present item.
    NSArray *Children = [dictionary objectForKey:@"Children"];

    if([Children count] == 0) {

        DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];
        [self.navigationController pushViewController:dvController animated:YES];
        [dvController release];
    }
    else {

        //Prepare to tableview.
        RootViewController *rvController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:[NSBundle mainBundle]];

        //Increment the Current View
        rvController.CurrentLevel += 1;

        //Set the title;
        rvController.CurrentTitle = [dictionary objectForKey:@"Title"];

        //Push the new table view on the stack
        [self.navigationController pushViewController:rvController animated:YES];

        rvController.tableDataSource = Children;

        [rvController release];
    }
}

- (void)dealloc {
    [CurrentTitle release];
    [tableDataSource release];
    [super dealloc];
}

@end

Редактировать:

Моя попытка:

RootViewController.h

//
//  RootViewController.h
//  DrillDownApp
//
//  Created by iPhone SDK Articles on 3/8/09.
//  Copyright www.iPhoneSDKArticles.com 2009. 
//

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {

NSArray *tableDataSource;
    NSArray *otherDataSource;
NSString *CurrentTitle;
NSInteger CurrentLevel;
}

@property (nonatomic, retain) NSArray *tableDataSource;
@property (nonatomic, retain) NSArray *otherDataSource;
@property (nonatomic, retain) NSString *CurrentTitle;
@property (nonatomic, readwrite) NSInteger CurrentLevel;

@end

RootViewController.m

//
//  RootViewController.m
//  DrillDownApp
//
//  Created by iPhone SDK Articles on 3/8/09.
//  Copyright www.iPhoneSDKArticles.com 2009. 
//

#import "RootViewController.h"
#import "DrillDownAppAppDelegate.h"
#import "DetailViewController.h"

@implementation RootViewController

@synthesize tableDataSource, otherDataSource, CurrentTitle, CurrentLevel;


- (void)viewDidLoad {
    [super viewDidLoad];

    if(CurrentLevel == 0) {

        //Initialize our table data source
    NSArray *tempArray = [[NSArray alloc] init];
    self.tableDataSource = tempArray;
    self.otherDataSource = tempArray;
            [tempArray release];

    DrillDownAppAppDelegate *AppDelegate = (DrillDownAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    self.tableDataSource = [AppDelegate.data objectForKey:@"Rows"];
    self.otherDataSource = [AppDelegate.data objectForKey:@"Other"];

    self.navigationItem.title = @"Root";
}
else 
    self.navigationItem.title = CurrentTitle;   
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(CurrentLevel == 0)
        return 2;
    else
        return 1;
}


// Customize the number of rows in the table view.
//Not sure about this. When I select some cell from section 1, what will appear at didSelectRowAtIndexPath?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0 && CurrentLevel == 0)
        return [self.tableDataSource count];
    if(section == 1 && CurrentLevel == 0)
        return [self.tableDataSource count];
    else 
        return [self.tableDataSource count];
}

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

    if(section == 0 && CurrentLevel == 0)
        return nil;
    else
        return nil;
}


// 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] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    // Set up the cell... don't know how.

    //here is only tableDataSource
    NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.section];
    cell.textLabel.text = [dictionary objectForKey:@"Title"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    UIImage *rowImage = [UIImage imageNamed:[dictionary objectForKey:@"Image"]];
    cell.imageView.image = rowImage;

    return cell;
}

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

    //only tableDataSource
    NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row];

    //Get the children of the present item.
    NSArray *Children = [dictionary objectForKey:@"Children"];

    if([Children count] == 0) {

        DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];

        [self.navigationController pushViewController:dvController animated:YES];
        [dvController release];
    }
    else {

        //Prepare to tableview.
        RootViewController *rvController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:[NSBundle mainBundle]];

        //Increment the Current View
        rvController.CurrentLevel += 1;

        //Set the title;
        rvController.CurrentTitle = [dictionary objectForKey:@"Title"];

        //Push the new table view on the stack
        [self.navigationController pushViewController:rvController animated:YES];

        rvController.tableDataSource = Children;

        [rvController release];
    }
}

- (void)dealloc {
    [CurrentTitle release];
    [tableDataSource release];
    [otherDataSource release];
    [super dealloc];
}

@end

1 Ответ

1 голос
/ 29 сентября 2011
  • Создать второй массив для хранения данных для второго раздела
  • Заполните этот массив в viewDidLoad, используя клавишу @ "Other"
  • Используйте indexPath.section в соответствующих методах источника данных, чтобы вы знали, о каком разделе вас спрашивает табличное представление, и возвращаете объект / количество соответствующего массива. indexPath.section будет 0 для первого раздела и 1 для второго раздела.
  • Где бы вы ни использовали tableDataSource, вам нужно проверить, в каком разделе вы находитесь. Это либо передается как целое число (раздел), либо как часть indexpath (так что вы можете получить его через indexPath.section). Если вы находитесь в разделе 0, используйте tableDataSource, иначе, если вы находитесь в разделе 1, используйте otherDataSource.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...