2016-11-02 15 views
0

я должен создать UITableView, который содержит 2 пользовательских ячеек RestTime и ExerciseTime. Что после a ExerciseTime является RestTime ячейка. Вот дизайн моего Tableview:UITableViewCell не в правильном порядке после создания

Design TableView

И вот мой код реализации:

высота -клеток в

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     // RestTime 
     if (indexPath.row % 2 == 1) { 
      return 40.0f; 
     } 

     // ExerciseTime 
     else { 
      return 65.0f; 
     } 
    } 

-Количество клеток

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     return (self.preset.blocks.count * 2) - 1; 
    } 

-Cell для строки

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

        if(indexPath.row % 2 == 1) { 
        RestTimeTableViewCell *restTimeCell = (RestTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:RestTimeTableViewCellIdentifier forIndexPath:indexPath]; 
        RestTime *restTime = (RestTime *)[self.restTimeArray objectAtIndex:indexPath.row]; 
        //CustomCell 
        return restTimeCell; 
       }else{ 
        ExerciseTimeTableViewCell *exerciseTimecell = (ExerciseTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ExerciseTimeTableViewCellIdentifier forIndexPath:indexPath]; 

        //Cell index 
        int index = (int)(indexPath.row/2); 
        //exerciseTimes is a NSSet 
        ExerciseTime *exerciseTime = [self.preset.exerciseTimes.allObjects objectAtIndex:index]; 

        //CustomCell 
        return exerciseTimecell; 
       } 
       return nil; 
} 

И выход таков:

Output TableView

Я попытался тайному мой NSSet к NSMutableArray и его до сих пор в настоящее время работает.

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

         if(indexPath.row % 2 == 1) { 
         RestTimeTableViewCell *restTimeCell = (RestTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:RestTimeTableViewCellIdentifier forIndexPath:indexPath]; 
         RestTime *restTime = (RestTime *)[self.restTimeArray objectAtIndex:indexPath.row]; 
         //CustomCell 
         return restTimeCell; 
        }else{ 
         ExerciseTimeTableViewCell *exerciseTimecell = (ExerciseTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ExerciseTimeTableViewCellIdentifier forIndexPath:indexPath]; 


         NSMutableArray *array = [[self.preset.exerciseTimes allObjects] mutableCopy]; 
         int index = (int)(indexPath.row/2); 
         ExerciseTime *exerciseTime = [array objectAtIndex:index]; 

         //CustomCell 
         return exerciseTimecell; 
        } 
        return nil; 
    } 

Как вы можете видеть, что все ExerciseCell не в правильном порядке. Я не могу понять, почему он не находится в правильном индексе после создания ячейки. Я хочу, чтобы порядок сортировался к тому времени, когда его создал не алфавит abcdef ... или 123456 .... Может ли кто-нибудь помочь мне выяснить, в чем проблема и как ее решить.

+0

@Vinodh Да я следовать этой инструкции, и она имеет эту проблему – VMCuongOnStackOverflow

+1

'allObjects' не гарантирует заказ. Я не знаю, является ли 'blocks'' 'NSSet или иначе, но вы можете проверить логику этого. Из документа: 'Порядок объектов в массиве не определен. ' – Larme

+0

@ Larme это NSSet – VMCuongOnStackOverflow

ответ

1

Я нашел проблему, и вначале NSSet не сортировался, и я отсортировал ее с помощью @ "createdTime", и моя проблема была решена.

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createdTime" ascending:YES]; 
NSArray *sortedArray = [self.exerciseTimes sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]]; 

Exercise *exerciseTime = (Exercise *)[sortedArray objectAtIndex:indexPath.row/2]; 
0

Пожалуйста, найти свой рабочий код и скриншот

@interface ViewController() 

@property (weak, nonatomic) IBOutlet UITableView *messageTableView; 

@property (retain, nonatomic) NSMutableArray *datasourceArray; 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
     // Do any additional setup after loading the view, typically from a nib. 

    [self.messageTableView registerNib:[UINib nibWithNibName:@"RestTimeTableViewCell" bundle:nil] forCellReuseIdentifier:@"RestTime"]; 
    [self.messageTableView registerNib:[UINib nibWithNibName:@"ExerciseTimeTableViewCell" bundle:nil] forCellReuseIdentifier:@"ExerciseTime"]; 

    self.messageTableView.separatorColor = [UIColor blackColor]; 
    self.messageTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 

    self.datasourceArray = [[NSMutableArray alloc]init]; 
    for (int i = 1; i <= 20; i++) { 
     [self.datasourceArray addObject:[NSString stringWithFormat:@"%d%d%d%d",i,i,i,i]]; 
    } 


} 


- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
     // Dispose of any resources that can be recreated. 
} 


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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return self.datasourceArray.count * 2; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
     // RestTime 
    if (indexPath.row % 2 == 1) { 
     return 40.0f; 
    } 
     // ExerciseTime 
    else { 
     return 65.0f; 
    } 
} 

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

    if (indexPath.row % 2 == 1) { 
     RestTimeTableViewCell *restTimeCell = (RestTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"RestTime" forIndexPath:indexPath]; 
      //Access you object from array like this 

     return restTimeCell; 
    } 
    else { 
     ExerciseTimeTableViewCell *exerciseTimecell = (ExerciseTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ExerciseTime" forIndexPath:indexPath]; 
      //Access you object from array like this 
     int index = (int)(indexPath.row/2); 

     exerciseTimecell.exerciseName.text = [self.datasourceArray objectAtIndex:index]; 
     return exerciseTimecell; 
    } 
} 
@end 

Скриншот

enter image description here

+0

Я хочу, чтобы порядок сортировался по времени его созданного алфавита abcdef ... или 123456 ... – VMCuongOnStackOverflow

+0

Извините, я не был чист. – VMCuongOnStackOverflow

+0

. См. Мой обновленный ответ. – Vinodh

0

NSSet просто набор, нет никакого порядка между объектами. Если вы хотите сохранить заказ, вы можете использовать NSArray (или NSMutableArray) вместо NSSet.

+0

Я пробовал это и не работает – VMCuongOnStackOverflow

+0

попробуйте использовать self.preset.exerciseTimes [index] вместо allObjects [index]. –

+0

@VMCuongOnStackOverflow: Для получения дополнительной информации: в ObjC есть 3 регулярных набора. ** Первая ** - 'NSSet', это просто простой набор, поэтому нет порядка между объектами (случайный порядок). ** Второй ** - 'NSArray/NSMutableArray', это упорядоченный набор, возвращающий объект через свой индекс. ** Третий ** - 'NSDictionary/NSMutableDictionary', это набор без упорядоченного, извлечения объекта через ключ. –