Я довольно новичок в программировании любого рода устройств и нахожусь на крутой кривой обучения, поэтому, пожалуйста, прости меня, если это не имеет большого смысла, или код в вопросе ужасен - мы все должны с чего-то начать и поверитья, я прочитал и прочитал и прочитал!
Я создаю таблицу из plist, который представляет собой массив словарей - он мне нужен в этом формате, так как позже я хочу иметь возможность изменять некоторые значенияи напишите обратно к соответствующему списку ключей.Я надеюсь, что кто-то сможет взглянуть на это и дать мне несколько советов о том, как ...
- Заставить таблицу отсортировать данные по ключу / значению 'name' из plistв моде от A до Z в сгруппированном стиле - кажется, это нормально, однако создает количество разделов в соответствии с количеством словарей в массиве в листе, в то время как некоторые из словарей должны быть сгруппированы в одном разделе(см. ниже)
- Разделите таблицу на разделы согласно пунктам в списке, т.е.если у меня есть 7 элементов в алфавитном порядке, то я хочу 7 разделов.
- имеет индекс справа, который содержит только соответствующее количество записей - если у меня нет данных в разделе «Q», тоЯ не хочу, чтобы 'Q' показывалось в индексе!
Очевидно, я очень далек от того, чтобы разобраться со всем этим - сам код на данный момент является чем-то вроде "собачьего обеда"поскольку я пробовал так много разных вещей без особого успеха, поэтому, если вы видите что-то, что вам не нравится, пожалуйста, дайте мне знать!
Я пытался прочитать все соответствующие разделы, такие как UILocalizedIndexedCollation и sortedArrayUsingDescriptors, ноя думаю, что мой мозг просто не в силах ...
Любой и все советы (кроме «брось это, ты недостаточно умел для этого», так как я никогда не сдамся ни с чем, я начинаю!) был быочень признателен!
(в начале было синтезировано много неиспользуемых переменных - я вынул соответствующий код, чтобы упростить то, что я написал здесь,Код компилируется без проблем и работает, давая мне следующий результат: таблица с 27 индексированными буквами справа, из которых работает только AJ (что соответствует количеству секций, созданных в таблице - есть только секция AJ).Содержимое ячеек - именно то, что я хочу.)
#import "RootViewController.h"
#import "View2Controller.h"
#import "tableviewsAppDelegate.h"
#import "SecondViewController.h"
#import "HardwareRootViewController.h"
#import "HardwareSecondViewController.h"
#import "SoftwareRootViewController.h"
@implementation SoftwareRootViewController
@synthesize dataList2;
@synthesize names;
@synthesize keys;
@synthesize tempImageType;
@synthesize tempImageName;
@synthesize finalImageName;
@synthesize tempSubtitle;
@synthesize finalSubtitleName;
@synthesize tempSubtitleType;
@synthesize finalSubtitleText;
@synthesize sortedArray;
@synthesize cellName;
@synthesize rowName;
//Creates grouped tableview//
- (id)initWithStyle:(UITableViewStyle)style {
if (self = [super initWithStyle:UITableViewStyleGrouped]) {
}
return self;
}
- (void)viewDidLoad {
//loads in backgroundimage and creates page title//
NSString *backgroundPath = [[NSBundle mainBundle] pathForResource:@"background1" ofType:@"png"];
UIImage *backgroundImage = [UIImage imageWithContentsOfFile:backgroundPath];
UIColor *backgroundColor = [[UIColor alloc] initWithPatternImage:backgroundImage];
self.tableView.backgroundColor = backgroundColor;
[backgroundColor release];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:.5 green:.4 blue:.3 alpha:5];
self.title = @"Software";
[super viewDidLoad];
//Defines path for DATA For ARRAY//
NSString *path = [[NSBundle mainBundle] pathForResource:@"DataDetail3" ofType:@"plist"];
//initialises the contents of the ARRAY with the PLIST//
NSMutableArray* nameArray = [[NSMutableArray alloc]
initWithContentsOfFile:path];
//Sorts the items in the list alphabetically//
NSSortDescriptor *nameSorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
[nameArray sortUsingDescriptors:[NSArray arrayWithObject:nameSorter]];
[nameSorter release];
self.dataList2 = nameArray;
[nameArray release];
}
- (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 anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}
#pragma mark Table view methods
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SectionsTableIdentifier ];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier: SectionsTableIdentifier ] autorelease];
}
// Configure the cell.
cell.indentationLevel = 1;
cell.textLabel.text = [[self.dataList2 objectAtIndex:indexPath.row]
objectForKey:@"name"];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
//Detremines the cell color according to the value in 'owned' in the plist//
NSString *textColor = [[self.dataList2 objectAtIndex:indexPath.row]
objectForKey:@"owned"];
if ([textColor isEqualToString: @"greenColor"]) {
[cell setBackgroundColor:[UIColor colorWithRed:0.1 green:0.7 blue:0.1 alpha:1]];
}
if ([textColor isEqualToString: @"blackColor"]) {
[cell setBackgroundColor:[UIColor whiteColor]];
}
return cell;
}
// Code For Loading of The View2Controller//
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [[self.dataList2 objectAtIndex:indexPath.row]
objectForKey:@"name"];
NSString *rowTitle = CellIdentifier;
NSLog(@"rowTitle = %@", rowTitle);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
SecondViewController *second = [[SecondViewController alloc] init];
[second setCategory: rowTitle];
[self.navigationController pushViewController:second animated:YES];
[second release];
}
- (void)dealloc {
[dataList2 release];
[super dealloc];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [dataList2 count];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [dataList2 count]; ///Tells the table that it only needs the amount of cells listed in the DATALIST1 ARRAY//
}//
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)help
{
return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:help];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}
@end
Буду очень признателен за любой совет - в данный момент я работаю над этим около недели безуспешно и близок к тому, чтобы просто датьup, что я действительно не хочу делать!
Если худшее приходит к худшему, и я не могу этого сделать, кто-нибудь захочет написать функциональность для меня, за небольшую плату, конечно !! !!1024 *
Приветствия и вот надеются ...
Чубс