2013-03-01 7 views
28

Я хочу сделать tableView с несколькими разделами, но я не хочу использовать словарь. У меня есть два массива. Я хочу, чтобы первый массив был загружен в первом разделе, а второй во втором разделе.UITableView с несколькими разделами

У меня есть arrayOne с 3 элементами и arrayTwo с 4 элементами, чтобы их добавить и показать в разделах.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if(section == 0) 
     return resultArray.count; 
    else 
     return resultArray.count; 
} 

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


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    NSLog(@"Number of Sections"); 
    if(section == 0) 
     return @"Section 1"; 
    if(section == 1) 
     return @"Section 2"; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSLog(@"Table Cell Data"); 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate]; 

    if (indexPath.section==0) {  
     appDelegate = (MultipleDetailViewsWithNavigatorAppDelegate *)[[UIApplication sharedApplication] delegate]; 
     ObjectData *theCellData = [resultArray objectAtIndex:indexPath.row]; 
     NSString *cellValue =theCellData.category; 
     NSLog(@"Cell Values %@",cellValue); 
     cell.textLabel.text = cellValue; 
     return cell; 
    } 
    else { 
     ObjectData *theCellData = [resultArray objectAtIndex:indexPath.row]; 
     NSString *cellValue =theCellData.category; 
     cell.textLabel.text = cellValue; 
     return cell;  
    } 
} 
+1

В чем проблема, с которой вы сталкиваетесь? Ваш код выглядит правильно. – Rushi

+0

присвоение значения в ячейке дает раздел раздела раздела, не объявленный –

+0

Вы должны использовать indexPath.section, а не только раздел в cellForRowAtIndexPath. Остальная часть кода в порядке. – Rushi

ответ

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
     if (section==0) 
     { 
      return [array1 count]; 
     } 
     else{ 
      return [array2 count]; 
     } 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
     if(section == 0) 
      return @"Section 1"; 
     else 
      return @"Section 2"; 
} 


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

     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
     } 

if (indexPath.section==0) { 
    ObjectData *theCellData = [array1 objectAtIndex:indexPath.row]; 
    NSString *cellValue =theCellData.category; 
    cell.textLabel.text = cellValue; 
} 
else { 
    ObjectData *theCellData = [array2 objectAtIndex:indexPath.row]; 
    NSString *cellValue =theCellData.category; 
    cell.textLabel.text = cellValue; 
} 
    return cell;   
} 
+0

Это - (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) раздел { if (indexPath.раздел == 0) { возвращение [массив1 кол-во]; } else { return [array1 count]; } } неправильный. Вы не можете получить indexPath.section здесь. – Rushi

+0

Да, ур правильно отредактировал спасибо Rushi –

+0

он не отображает значения в значениях ячейки –

0

Изменить этот if (section==0)

в if (indexPath.section==0)

Вы должны выполнять эту функцию:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if(section == 0) 
     return arrSection1.count; 
     else 
     return arrSection2.count; 
} 
+0

снова это ошибка, я сделал, как этот indexPath.section –

+0

@NaziaJan Проверьте отредактированный код – Rushi

+0

@ NaziaJan выполнил эту функцию? – Rushi

0

Ваш numberOfRowsInSection должно быть что-то вроде этого:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if (section == 0) { 
     return firstArray.count; 
    } else { 
     return secondArray.count; 
    } 
} 
0

Вы практически на правильном пути ....

Рассмотрим две ваши массивы arrOne и arrTwo .....

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
     if(section == 0) 
     return [arrOne count]; 
     else 
     return [arrTwo count]; 
    } 

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

     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
      } 

      if (indexPath.section==0) { 


     ObjectData *theCellData = [arrOne objectAtIndex:indexPath.row]; 
     NSString *cellValue =theCellData.category; 
     NSLog(@"cellValue = %@",cellValue); //To see the value of string cellValue 
     cell.textLabel.text = cellValue; 

     return cell; 

    } 

    else { 
     ObjectData *theCellData = [arrTwo objectAtIndex:indexPath.row]; 
     NSString *cellValue =theCellData.category; 
     cell.textLabel.text = cellValue; 

     return cell;   
    } 
} 
+0

он дает ошибку в indexpath.section –

+0

Я думаю, P должен быть капиталом в pathpath, .... отредактировал это. Теперь попробуйте, он должен работать. –

+0

работает, но не показывает значения ячейки –

0

TableView Делегат метод уже дают сечение, : (NSInteger) раздел .. поэтому мы можем также использовать switchCase

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     switch (section) 
     { 
      case 0: 
       return self.arrMedia.count; 
       break; 
      case 1: 
       return 1; 
       break; 
     } 
     return 0; 
    } 
0

Вот соответствующая Swift 3 линия:

func numberOfSections (in tableView: UITableView) -> Int { 
    ... 
    return numberOfSections 
} 

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 
    //Not necessary, but will let you format the section headers. Example: 
    guard let header = view as? UITableViewHeaderFooterView else { return } 
    header.textLabel?.font = UIFont.boldSystemFont(ofSize: 24) 
    header.textLabel?.textColor = UIColor.darkGray 
    header.textLabel?.textAlignment = .center 
    header.textLabel?.frame = header.frame 
    view.tintColor = UIColor.white 
} 

func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { 
    //Also not necessary, but clear footers help space out sections 
    view.tintColor = UIColor.clear 
} 

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { 
    //Spacing between sections: 
    return 25 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    ... 
    return sectionCount 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    //All your cell setup 
    ... 
    //I call this to get the absolute row number (disregarding sections) 
    let row = getAbsoluteRow_InCurrentSection(indexPath: indexPath) 
    //Now you can use the row number to grab a value from an array or CoreData object and use the value to populate your cell!! 
} 

func getAbsoluteRow_InCurrentSection(indexPath: IndexPath) -> Int { 
    var aggRows = 0 
    if currentListEntity == "GrocTask" { 
     let curSection = indexPath.section 
     for i in 0..<curSection { 
      aggRows += flex1ArrayCnt[i] 
     } 
     aggRows += indexPath.row 
    } 
    return aggRows 
} 

// Обратите внимание, я только включен которые имеют непосредственное отношение к созданию UITableView с разделами. Я не включил функции editActions, didSelect или другие функции делегата UITableView.

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