Я довольно новичок в программировании любого устройства и на крутой кривой обучения, поэтому, пожалуйста, простите меня, если это не делает слишком много смысла или код в вопросе ужасен - Мы все должны начать с чего-то, и верьте мне, я читал, читал и читал!iPhone - создание таблицы в разрезе и в алфавитном порядке
Я создаю таблицу из plist, которая представляет собой массив словарей - мне это нужно в этом формате, поскольку позже я хочу иметь возможность изменять некоторые значения и записывать обратно в соответствующий «ключ» plist. Я надеюсь, что кто-то будет в состоянии смотреть на это и дать мне некоторые указатели о том, как ...
- Сделайте таблицу сортировки данных под «именем» ключ/значение из списка свойств в мода от A до Z в сгруппированном стиле - это, похоже, хорошо, однако он создает количество разделов в соответствии с количеством словарей в массиве в plist, тогда как некоторые словари должны быть сгруппированы вместе в одном разделе (см. ниже)
- Разделите стол на секции в соответствии с элементами в пластине, т.е. если у меня есть 7 элементов, начиная с алфавита, тогда я хочу 7 разделов.
- имеют индекс с правой стороны, который имеет только соответствующее количество записей - если у меня нет данных под «Q», тогда я не хочу, чтобы «Q» отображался в индексе!
Очевидно, что я далеко от сортировки всего этого - сам код - это немного «ужины с собаками» на данный момент, поскольку я много раз пробовал много разных вещей, поэтому, если вы видите что-то, что вам не нравится, пожалуйста, дайте мне знать!
Я пытался читать на всех соответствующих разделах, таких как UILocalizedIndexedCollation и sortedArrayUsingDescriptors, но я предполагаю, что мой мозг как раз не до него ...
Любые и все советы (кроме «дать его вам» я не достаточно яркий для этого, так как я никогда не отказываюсь от чего-либо, что я начинаю!) было бы очень признательно!
(есть много неиспользуемых переменных, синтезированных в начале - я взял соответствующий код, чтобы упростить то, что я разместил здесь, код компилируется без проблем и работает, дал мне следующий результат: a таблица с 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
Любой совет будет очень благодарен - на данный момент я работаю над этим в течение недели без успеха и близко к тому, чтобы просто сдаваться, чего я действительно не хочу делать!
Если худшее пришло к худшему, и я не могу это сделать, я бы хотел написать функциональность для меня, за небольшую плату, конечно!
Приветствия и Heres надеясь ...
голавли