Iphone Сгруппированный просмотр таблицы с nib-файлом за строкой, мои строки перезапускаются в каждом разделе, и он не будет отображать строки следующего раздела - PullRequest
0 голосов
/ 05 октября 2010

Я начинаю с SDK и пытаюсь настроить приложение, используя табличное представление для отображения информации.

Я создал базовое приложение для окна, и я использую панель вкладок с табличным представлением.у него есть панель навигации для перемещения вперед и назад , и она прекрасно работает "очевидно", но у меня проблема в том, что Всякий раз, когда вы нажимаете на первый ряд каждого (1, 2,3 ...) раздел, который вызывает первую строку первого раздела, , и я провел много исследований: учебные пособия, книги, форумы, но, кажется, не могу найти способ сделать этоРабота.Я нашел много полезной информации, хотя это мне очень помогло, но не решило бы мою проблему.Я занимался этим несколько дней и дней.

Поэтому, перепробовав все ресурсы, которые мне удалось найти, я обращаюсь к вам за помощью.

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

// Я использую это в MyTableViewController.h {

#import <UIKit/UIKit.h>
#import "firstCustomCell.h"

@interface MyTableViewController : UITableViewController <UITableViewDelegate,UITableViewDataSource> {

IBOutlet UITableView *theTableView;
NSMutableArray *firstArray;
NSMutableArray *secondArray;
NSMutableArray *thirdArray;
NSMutableArray *listOfItems; 
  }

   @property (nonatomic, retain) NSMutableArray *firstArray;
   @property (nonatomic, retain) NSMutableArray *secondArray;
   @property (nonatomic, retain) NSMutableArray *thirdArray;
   @property (nonatomic, retain) NSMutableArray *listOfItems;

   @end

   }

// Затем в реализации я использую This: tableViewController.m

#import "MyTableViewController.h"
#import "One.h"
#import "Two.h"
#import "Three.h"
#import "Four.h"
#import "Five.h"
#import "Six.h"
#import "Seven.h"
#import "Eight.h"
#import "Nine.h"
#import "Ten.h"
#import "Eleven.h"
#import "Twelve.h"

@implementation MyTableViewController

@synthesize firstArray;
@synthesize secondArray;
@synthesize thirdArray;
@synthesize listOfItems;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
[super viewDidLoad];

listOfItems = [[NSMutableArray alloc]init];

firstArray = [[NSMutableArray alloc]init];
[firstArray addObject:@"Week One"];
[firstArray addObject:@"Week Two"];
[firstArray addObject:@"Week Three"];


NSDictionary *firstDic = [NSDictionary dictionaryWithObject:firstArray forKey:@"CompoNente"];

secondArray = [[NSMutableArray alloc]init];
[secondArray addObject:@"Week Four"];
[secondArray addObject:@"Week Five"];
[secondArray addObject:@"Week Six"];
[secondArray addObject:@"Week Seven"];


NSDictionary *secondDic = [NSDictionary dictionaryWithObject:secondArray forKey:@"CompoNente"];

thirdArray = [[NSMutableArray alloc]init];
[thirdArray addObject:@"Week Eight"];
[thirdArray addObject:@"Week Nine"];
[thirdArray addObject:@"Week Ten"];
[thirdArray addObject:@"Week Eleven"];
[thirdArray addObject:@"Week Twelve"];

NSDictionary *thirdDic = [NSDictionary dictionaryWithObject:thirdArray forKey:@"CompoNente"];


[listOfItems addObject:firstDic];
[listOfItems addObject:secondDic];
[listOfItems addObject:thirdDic];


self.title = NSLocalizedString(@"TableView", @"My favorite TableView");




#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return [listOfItems count];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  {
// Return the number of rows in the section.

NSDictionary *dictionary = [listOfItems objectAtIndex:section];
NSArray *array = [dictionary objectForKey:@"CompoNente"];
return [array count];

// Настройка внешнего вида ячеек табличного представления.

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

static NSString *CellIdentifier = @"ScustomCell";

firstCustomCell *cell = (firstCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

NSLog(@"Cell created");

NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"firstCustomCell" owner:nil options:nil];

for(id currentObject in nibObjects) {

if ([currentObject isKindOfClass:[firstCustomCell class]]) {
 cell = (firstCustomCell *)currentObject;
}

}
  }

 switch (indexPath.row) {
  case 0:
   (indexPath.section == 0, indexPath.row == 0);
   [[cell currentNameLabel] setText:@"Week One"];
   [[cell imageView] setImage:[UIImage imageNamed:@"1.png"]];
   break;
  case 1:
   (indexPath.section == 0, indexPath.row == 1);
   [[cell currentNameLabel] setText:@"Week Two"];
   [[cell imageView] setImage:[UIImage imageNamed:@"2.png"]];
   break;
  case 2: 
   (indexPath.section == 0, indexPath.row %12 == 2);
   [[cell currentNameLabel] setText:@"Week Three"];
   [[cell imageView] setImage:[UIImage imageNamed:@"3.png"]];
   break;
  case 3:
   (indexPath.section == 1, indexPath.row %12 == 0);
   [[cell currentNameLabel] setText:@"Week Four"];
   [[cell imageView] setImage:[UIImage imageNamed:@"4.png"]];
   break;
  case 4:
   (indexPath.section == 1, indexPath.row %12 == 1);
   [[cell currentNameLabel] setText:@"Week Five"];
   [[cell imageView] setImage:[UIImage imageNamed:@"5.png"]];
   break;
  case 5:
   (indexPath.section == 1, indexPath.row %12 == 2);
   [[cell currentNameLabel] setText:@"Week Six"];
   [[cell imageView] setImage:[UIImage imageNamed:@"6.png"]];
   break;
  case 6:
   (indexPath.section == 1, indexPath.row %12 == 3);
   [[cell currentNameLabel] setText:@"Week Seven"];
   [[cell imageView] setImage:[UIImage imageNamed:@"7.png"]];
   break;
  case 7:
   (indexPath.section == 2, indexPath.row %12 == 0);
   [[cell currentNameLabel] setText:@"Week Eight"];
   [[cell imageView] setImage:[UIImage imageNamed:@"8.png"]];
   break;
  case 8:
   (indexPath.section == 2, indexPath.row %12 == 1);
   [[cell currentNameLabel] setText:@"Week Nine"];
   [[cell imageView] setImage:[UIImage imageNamed:@"9.png"]];
   break;
  case 9:
   (indexPath.section == 2, indexPath.row %12 == 2);
   [[cell currentNameLabel] setText:@"Week Ten"];
   [[cell imageView] setImage:[UIImage imageNamed:@"10.png"]];
   break;
  case 10:
   (indexPath.section == 2, indexPath.row %12 == 3);
   [[cell currentNameLabel] setText:@"Week Eleven"];
   [[cell imageView] setImage:[UIImage imageNamed:@"11.png"]];
   break;
  case 11:
   (indexPath.section == 2, indexPath.row %12 == 4);
   [[cell currentNameLabel] setText:@"Week Twelve"];
   [[cell imageView] setImage:[UIImage imageNamed:@"12.png"]];
   break;

 }

// Настройкаcell ...

NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"CompoNente"];
NSString *cellValue = [array objectAtIndex:indexPath.row];

cell.text = cellValue; //also receive a warning that setText is deprecated.


return cell;

}   

// Затем делегат

#pragma mark -
#pragma mark Table view delegate

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

 [tableView deselectRowAtIndexPath:indexPath animated:YES];

 if ([[firstArray objectAtIndex:indexPath.row] isEqual: @"Week One"]) {

  One *one = [[One alloc]initWithNibName:@"One" bundle:nil];
  [self.navigationController pushViewController:one animated:YES];
  [one release];

 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Two"]) {

  Two *two = [[Two alloc]initWithNibName:@"Two" bundle:nil];
  [self.navigationController pushViewController:two animated:YES];
  [two release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Three"]) {

   Three *three = [[Three alloc]initWithNibName:@"Three" bundle:nil];
  [self.navigationController pushViewController:three animated:YES];
  [three release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Four"]) {

  Four *four = [[Four alloc]initWithNibName:@"Four" bundle:nil];
  [self.navigationController pushViewController:four animated:YES];
  [four release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Five"]) {

  Five *five = [[Five alloc]initWithNibName:@"Five" bundle:nil];
  [self.navigationController pushViewController:five animated:YES];
  [five release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Six"]) {

  Six *six = [[Six alloc]initWithNibName:@"Six" bundle:nil];
  [self.navigationController pushViewController:six animated:YES];
  [six release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Seven"]) {

  Seven *seven = [[Seven alloc]initWithNibName:@"Seven" bundle:nil];
  [self.navigationController pushViewController:seven animated:YES];
  [seven release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Eight"]) {

  Eight *eight = [[Eight alloc]initWithNibName:@"Eight" bundle:nil];
  [self.navigationController pushViewController:eight animated:YES];
  [eight release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Nine"]) {

  Nine *nine = [[Nine alloc]initWithNibName:@"Nine" bundle:nil];
  [self.navigationController pushViewController:nine animated:YES];
  [nine release]; 
 }


 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Ten"]) {

  Ten *ten = [[Ten alloc]initWithNibName:@"Ten" bundle:nil];
  [self.navigationController pushViewController:ten animated:YES];
  [ten release]; 
 }

 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Eleven"]) {

  Eleven *eleven = [[Eleven alloc]initWithNibName:@"Eleven" bundle:nil];
  [self.navigationController pushViewController:eleven animated:YES];
  [eleven release]; 
 }
 else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Twelve"]) {

  Twelve *twelve = [[Twelve alloc]initWithNibName:@"Twelve" bundle:nil];
  [self.navigationController pushViewController:twelve animated:YES];
  [twelve release]; 
 }
}

// добавляем заголовки для секций

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

if (section == 0)
 return @"FIRST SECTION";

 else if (section == 1)
  return @"SECOND SECTION";

 else if (section == 2)
  return @"THIRD SECTION";

} // also receive a warning "Control reaches end of non-void function"

// Освобождаем или очищаем память Аотделка TableView

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
 [listOfItems release];
 [thirdArray release];
 [secondArray release];
 [firstArray release];
    [super dealloc];
}


@end

Ответы [ 2 ]

0 голосов
/ 05 октября 2010

в - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath вы просто игнорируете indexpath.section.Нет вызова, который учитывает раздел.


работают заголовки вашего раздела или нет?Для меня это выглядит нормально.
Добавьте return nil;, добавьте конец этого метода, чтобы избавиться от этого предупреждения.Вы получаете это предупреждение, потому что вы ничего не возвращаете, если раздел больше 2.


 if ([[firstArray objectAtIndex:indexPath.row] isEqual: @"Week One"]) {

  One *one = [[One alloc]initWithNibName:@"One" bundle:nil];
  [self.navigationController pushViewController:one animated:YES];
   [one release];

  }

  else if ([[firstArray objectAtIndex:indexPath.row] isEqual:@"Week Two"]) {

   Two *two = [[Two alloc]initWithNibName:@"Two" bundle:nil];
   [self.navigationController pushViewController:two animated:YES];
   [two release]; 
  }

эм, вы действительно создали 10 разных классов с 10 разными nib-файлами за 10 разных недель?Я сомневаюсь, что это действительно необходимо.Это позволит вам много копировать и вставлять, если ваши клиенты будут нуждаться в поддержке в течение 52 недель в следующей версии ;-)

0 голосов
/ 05 октября 2010

Да, у меня всегда есть эта проблема - я не уверен, что это такое, но я думаю, что это как-то связано с тем фактом, что == 0 также == NO или == false, но я не уверен.

Что обычно работает для меня, так это трактовать это как целое число, поэтому:

if([indexPath section] < 1){
  // section 0
}
else if([indexPath section] > 0 && [indexPath section] < 2){
  // section 1
}
else{
  // etc...
}

или вы можете преобразовать его в строку NSString

NSString *section = [NSString stringWithFormat:@"%i",[indexPath section]];

, а затем выполните сравнение строк:

if([section isEqualToString:@"0"]){
  // first section
}
else if([section isEqualToString:@"1"]){
  // next section
}
else {
  // etc...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...