2016-02-02 4 views
0

enter image description hereCustomCell в UITableView в Objective C

Я приложил пример вывода здесь .... Он имеет две ячейки первого из них, имеющие functioncode, StartTime, время окончания и второй имеет время перерыва.

Теперь хочу я хочу сделать, это третий один должен содержать functionCode:, время_запуска:, время окончания :,

Мой массив имеет 3 словаря

(
     { 
     date = "2016-01-20"; 
     "end_time" = "11:10:00"; 
     "function_code" = RCV; 
     "operator_id" = JOHN; 
     "start_time" = "11:00:00"; 
     "total_time" = 10; 
     "total_units" = 19; 
    }, 
     { 
     "break_time" = 65; 
    }, 
     { 
     date = "2016-01-20"; 
     "end_time" = "12:25:00"; 
     "function_code" = PIK; 
     "operator_id" = JOHN; 
     "start_time" = "12:15:00"; 
     "total_time" = 10; 
     "total_units" = 26; 
    }) 

Это мой cellforrow по методу indexpath

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

    if (indexPath.row ==0) 
    { 

     self.tempDictionary = [self.arrData1 objectAtIndex:indexPath.row]; 
     NSLog(@"The dictionary contains:%@",self.tempDictionary); 


     static NSString *CellIndentifier [email protected]"TableViewCell"; 
     TableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIndentifier]; 

     if (cell == nil) { 
      cell = [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier]; 

     } 

     NSLog(@" the dictionary contains all :%@",self.tempDictionary); 


     NSString *strFunctionCodeValue =[self.tempDictionary objectForKey:@"function_code"]; 
     NSString *strStartTimeValue = [self.tempDictionary objectForKey:@"start_time"]; 
     NSString *strEndTimeValue = [self.tempDictionary objectForKey:@"end_time"]; 
     NSString *strTotalUnitsValue =[self.tempDictionary objectForKey:@"total_units"]; 
     NSString *strTotalTimeValue = [self.tempDictionary objectForKey:@"total_time"]; 


     cell.lblFunctionCodeValue.text = strFunctionCodeValue; 
     cell.lblStartTimeValue.text = strStartTimeValue; 
     cell.lblEndTimeValue.text = strEndTimeValue; 
     cell.lblTotalUnitsValue.text =strTotalUnitsValue; 
     cell.lblTotalTimeValue.text = strTotalTimeValue; 

     return cell; 

    } 
    else 
    { 

     static NSString *cellIdentifier1 [email protected]"TableViewCell1"; 
     self.tempDictionary = [self.arrData1 objectAtIndex:indexPath.row]; 
     NSLog(@" dicitionary :%@",self.tempDictionary); 

     TableViewCell1 *cell1 =(TableViewCell1 *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier1]; 
     if (cell1 == nil) { 
      cell1 =[[TableViewCell1 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1]; 

     } 

     NSString *breakTimeValue = [self.tempDictionary objectForKey:@"break_time"]; 
     cell1.lblBreakTimeValue.text = breakTimeValue; 

     return cell1; 

    } 

} 

ответ

2

Сделать класс с именем MyObject наследовать от NSObject. Он будет содержать следующие свойства: date, end_time, function_code, operator_id, start_time, total_time, total_units.

Тогда вы сделаете еще один класс MyObject2, содержащий только одно свойство ** break_time **.

Вы проанализируете словарь в соответствующих моделях, добавив проверку, если все слова в словаре больше 1, это означает, что вам нужно проанализировать свои данные в myObject1, иначе вы проанализируете его в myObject2. Вы будете добавлять эти анализируемые объекты в свой массив, которые могут быть использованы в качестве источника данных для uitableview. Теперь в методе делегата tableview cellForRowAtIndexPath вам нужно всего лишь выполнить проверку.

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

    id *object = [array objectAtIndex:indexPath.row]; 
    if([object isKindOfClass:MyObject]){ 
     CustomCell1 *cell1 = (CustomCell1 *)[tableView dequeueReusableCellWithIdentifier:@"CustomCell1"]; 
     return cell1; 
    }else{ 
     CustomCell2 *cell2 = (CustomCell2 *)[tableView dequeueReusableCellWithIdentifier:@"CustomCell2"]; 
     return cell2; 
    } 
    return; 
} 

На ваш существующий код вы можете добавить чек.

self.tempDictionary = [self.arrData1 objectAtIndex:indexPath.row]; 
if([[self.tempDictionary allKeys] count]>1){ 
     static NSString *CellIndentifier [email protected]"TableViewCell"; 
    TableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIndentifier]; 

    if (cell == nil) { 
     cell = [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier]; 

    } 

    NSLog(@" the dictionary contains all :%@",self.tempDictionary); 

    NSString *strFunctionCodeValue =[self.tempDictionary objectForKey:@"function_code"]; 
    NSString *strStartTimeValue = [self.tempDictionary objectForKey:@"start_time"]; 
    NSString *strEndTimeValue = [self.tempDictionary objectForKey:@"end_time"]; 
    NSString *strTotalUnitsValue =[self.tempDictionary objectForKey:@"total_units"]; 
    NSString *strTotalTimeValue = [self.tempDictionary objectForKey:@"total_time"]; 


    cell.lblFunctionCodeValue.text = strFunctionCodeValue; 
    cell.lblStartTimeValue.text = strStartTimeValue; 
    cell.lblEndTimeValue.text = strEndTimeValue; 
    cell.lblTotalUnitsValue.text =strTotalUnitsValue; 
    cell.lblTotalTimeValue.text = strTotalTimeValue; 


}else{ 
    static NSString *cellIdentifier1 [email protected]"TableViewCell1"; 
    self.tempDictionary = [self.arrData1 objectAtIndex:indexPath.row]; 
    NSLog(@" dicitionary :%@",self.tempDictionary); 

    TableViewCell1 *cell1 =(TableViewCell1 *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier1]; 
    if (cell1 == nil) { 
     cell1 =[[TableViewCell1 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1]; 

} 


    NSString *breakTimeValue = [self.tempDictionary objectForKey:@"break_time"]; 

    cell1.lblBreakTimeValue.text = breakTimeValue; 


    return cell1; 
} 
+0

Спасибо @shehzad Ali, я получил ошибку, так как управление может дойти до конца не-void функции, –

+0

return nil в конце функции. –

+0

ya я использовал return nil в конце функции, приложение получило сбой. «NSInternalInconsistencyException», причина: «UITableView dataSource должен вернуть ячейку из tableView: cellForRowAtIndexPath:« это ошибка –

0

В чем вопрос?

Возможно, вам нужно построить 2 разных ячейки, и в зависимости от некоторых данных вы возвращаете то или другое в cellForRow.

+0

благодаря @Ricardo, я хочу построить 2 разные клетки, пожалуйста, помогите мне сделать это, –

+0

Просто добавьте две ячейки в раскадровке и назначить их 2 разных подклассов, каждый из которых с разных точек. Не забудьте использовать 2 разных CellIdentifiers (например, используйте имя класса). – Ricardo

+0

И в коде возвратите тот, который вы хотите для определенной строки. В cellForRow – Ricardo

 Смежные вопросы

  • Нет связанных вопросов^_^