Подтвердить что ты не робот

Расширяемый tableView в iphone

enter image description here

Я хочу сделать этот вид табличного представления расширяемого/сбрасываемого. есть категории и подкатегории, как на картинке. например, "здоровье и красота" - это категория, и когда я нажимаю эту ячейку, чем ее открытые подкатегории, как на рисунке ниже. Итак, как я могу сделать этот вид таблицы? пожалуйста, предложите мне.

4b9b3361

Ответ 2

Используйте следующий код для расширяемой ячейки в UITableView

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text=[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"name"];
    [cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"level"] intValue]];    
    return cell;
}

код для расширения & сворачивающиеся строки - метод TableSDidSelectRow

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *d=[self.arForTable objectAtIndex:indexPath.row];
    if([d valueForKey:@"Objects"]) {
        NSArray *ar=[d valueForKey:@"Objects"];
        BOOL isAlreadyInserted=NO;
        for(NSDictionary *dInner in ar ){
            NSInteger index=[self.arForTable indexOfObjectIdenticalTo:dInner];
            isAlreadyInserted=(index>0 && index!=NSIntegerMax);
            if(isAlreadyInserted) break; 
        }
        if(isAlreadyInserted) {
            [self miniMizeThisRows:ar];
        } else {        
            NSUInteger count=indexPath.row+1;
            NSMutableArray *arCells=[NSMutableArray array];
            for(NSDictionary *dInner in ar ) {
                [arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
                [self.arForTable insertObject:dInner atIndex:count++];
            }
            [tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
        }
    }
}

Метод, который поможет минимизировать & увеличить/развернуть-свернуть строки.

-(void)miniMizeThisRows:(NSArray*)ar{
    for(NSDictionary *dInner in ar ) {
        NSUInteger indexToRemove=[self.arForTable indexOfObjectIdenticalTo:dInner];        
        NSArray *arInner=[dInner valueForKey:@"Objects"];
        if(arInner && [arInner count]>0){
            [self miniMizeThisRows:arInner];
        }
        if([self.arForTable indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
            [self.arForTable removeObjectIdenticalTo:dInner];
            [self.tableView deleteRowsAtIndexPaths:
              [NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexToRemove inSection:0]]
                      withRowAnimation:UITableViewRowAnimationRight];
        }
    }
}

Вы можете скачать исходный код с моего учебного сайта.

Ответ 4

У меня есть немного другой подход к расширяемым представлениям таблиц - тот, который согласуется с тем, как эти виды представлений таблиц обычно построены.

Есть заголовки и есть ячейки. Заголовки должны быть недоступны, а затем ячейки под заголовками будут отображаться или скрываться. Это может быть достигнуто добавлением распознавателя жестов в заголовок, и при нажатии, вы просто удалите все ячейки под этим заголовком (раздел) и наоборот (добавьте ячейки). Конечно, вы должны поддерживать состояние, в котором заголовки "открыты", а заголовки "закрыты".

Это приятно по нескольким причинам:

  • Работа с заголовками и ячейками разделяется, что делает очиститель кода.
  • Этот метод отлично сочетается с тем, как построены представления таблиц (заголовки и ячейки) и, следовательно, не так много магии - код просто удаляет или добавляет ячейки и должен быть совместим с более поздними версиями iOS.

Я сделал очень простую библиотеку, чтобы добиться этого. Пока ваше представление таблицы настроено с заголовками и ячейками раздела UITableView, все, что вам нужно сделать, это подкласс tableview и заголовок. Попробуйте:)

Ссылка: https://github.com/fuzz-productions/FZAccordionTableView

введите описание изображения здесь

Ответ 5

Попробуйте использовать этот код... Может быть, это может помочь. И не стесняйтесь редактировать код в соответствии с вашими требованиями...

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()

@end

@implementation ViewController
@synthesize myTable;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //myTable.backgroundColor=[UIColor clearColor];
   // self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    muArr= [[NSMutableArray alloc]initWithObjects:@"Vinay",@"Anmol",@"Jagriti", nil];
    ExpArr=[[NSMutableArray alloc]initWithObjects:@"Useeee",@"Thissss",@"Codeee", nil];
    otherExpand=100;
    checker=100;

}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return muArr.count;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(otherExpand==section)
    return ExpArr.count;

    return  0;

}

-(BOOL)tableView:(UITableView *)table canCollapse:(NSIndexPath *)indexPath
{

    return NO;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *[email protected]"Cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell==nil)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];

    }
    cell.textLabel.text=[ExpArr objectAtIndex:indexPath.row];
    cell.textLabel.backgroundColor=[UIColor clearColor];
    UIView *viewww=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    viewww.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    cell.backgroundView=viewww;

   // cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLineEtched];
    [tableView setSeparatorColor:[UIColor purpleColor]];

    return cell;

}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView *view1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [view1.layer setCornerRadius:20];
    view1.layer.borderWidth=2;
    view1.layer.borderColor=[UIColor brownColor].CGColor;
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 295, 44)];
    label.backgroundColor=[UIColor clearColor];

    label.text=[muArr objectAtIndex:section];
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    btn.frame=CGRectMake(280, -5, 50, 50);
    btn.backgroundColor=[UIColor clearColor];
    btn.tag=section;

    view1.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"wood.png"]];
    label.textColor=[UIColor blackColor];
    label.font=[UIFont fontWithName:@"American TypeWriter" size:18];
    //btn.backgroundColor=[UIColor blackColor];
    [view1 addSubview:btn];
    [view1 addSubview:label];

    [btn addTarget:self action:@selector(Btntap:) forControlEvents:UIControlEventTouchUpInside];

    return view1;
}


-(void)Btntap : (UIButton *)btn
{
    if(otherExpand!=100)
    {
        if (otherExpand==btn.tag)
        {
            NSMutableArray *tempArr2=[[NSMutableArray alloc]init];
            for(int j=0;j<ExpArr.count;j++)
            {
                NSIndexPath *indexx1=[NSIndexPath indexPathForRow:j inSection:otherExpand];
                [tempArr2 addObject:indexx1];
            }
            checker=0;
            otherExpand=100;
            [myTable deleteRowsAtIndexPaths:tempArr2 withRowAnimation:UITableViewRowAnimationAutomatic];
        }

        else
        {
            NSMutableArray *tempArr2=[[NSMutableArray alloc]init];
            for(int j=0;j<ExpArr.count;j++)
            {
                NSIndexPath *indexx1=[NSIndexPath indexPathForRow:j inSection:otherExpand];
                [tempArr2 addObject:indexx1];
            }
            checker=1;
            otherExpand=100;
            [myTable deleteRowsAtIndexPaths:tempArr2 withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }

    if(checker!=0)
    {
        otherExpand=btn.tag;
        //checker=
        NSMutableArray *tempArr=[[NSMutableArray alloc]init];
        for(int i=0;i<ExpArr.count;i++)
        {
            NSIndexPath *indexx=[NSIndexPath indexPathForRow:i inSection:btn.tag];
            [tempArr addObject:indexx];
        }
        [myTable insertRowsAtIndexPaths:tempArr withRowAnimation:UITableViewRowAnimationAutomatic];

        checker=1;
    }
    checker=100;
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

@end

Ответ 7

Вы можете взглянуть на этот аккордеонный пример в Swift: https://github.com/tadija/AEAccordion

enter image description here

У него очень мало кода для создания эффекта аккордеона (не используя разделы, кроме ячеек), и в качестве бонуса также существует решение использовать файлы XIB внутри других XIB файлов (полезно для пользовательских ячеек, которые используют пользовательские представления).

Ответ 9

TLIndexPathTools может делать это естественно. На самом деле существуют расширения для расширяемых разделов и расширяемых древовидных структур. Попробуйте запустить образец Collapse для расширяемых разделов и Примерный проект схемы для расширяемых деревьев.

Одним из преимуществ использования TLIndexPathTools является то, что в качестве простого низкоуровневого API он может решать все виды задач динамического представления таблиц и сбора данных с использованием общего подхода. И он работает взаимозаменяемо с Core Data и обычными массивами.

Ответ 10

Проверьте эту ссылку:

http://iostechnotips.blogspot.in/2014/05/expandable-uitableview.html

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

* Используйте UITableView метод делегата viewForHeaderInSection и верните пользовательский UIView.

* Добавить UIButton в качестве подвью с действием "expandable: (id) отправитель" проверить идентификатор отправителя как номер раздела и перезагрузить представление таблицы.

Ответ 11

В вашем .h файле

LoadCustomCell *cell1;
NSMutableArray  *arrayForBool;
NSMutableArray  *questionArray;
NSMutableArray  *answerArray;

В вашем .m файле

 viewDidLoadMethod {
 _faqTblView.estimatedRowHeight = 30;
 _faqTblView.rowHeight = UITableViewAutomaticDimension;
 arrayForBool = [[NSMutableArray alloc]init];

 _questionArray = [[NSMutableArray alloc]init];
 _answerArray = [[NSMutableArray alloc]init];
 for (int i = 0; i < _questionArray.count; i++) {
        [arrayForBool addObject:@"0"];
    }
    self.faqTblView.dataSource = self;
    self.faqTblView .delegate = self;
    [self.faqTblView reloadData];
 }

после этого

 #pragma mark - TableView Datasource & Delegate Method.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return [_questionArray count];
 }
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    UILabel *lblText = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 260, 100)];
    lblText.text = [_questionArray objectAtIndex:section];
    return [lblText getLabelHeight] + 20;(created custom class)
 }
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

UITapGestureRecognizer  *headerTapped   = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTapped:)];
cell1 = [[[NSBundle mainBundle] loadNibNamed:@"LoadCustomCell" owner:self options:nil] objectAtIndex:0];
[cell1 setFrame:CGRectMake(0, 0, cell1.frame.size.width, cell1.frame.size.height)];
NSString *numStr = [NSString stringWithFormat:@"%ld. ",section + 1];
[cell1.sideMenuUserNameLabel setText:[numStr stringByAppendingString:[_questionArray objectAtIndex:section]]];
[cell1 setBackgroundColor:[UIColor lightGrayColor]];
cell1.tag = section;
[cell1 addGestureRecognizer:headerTapped];

return cell1;
}

- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer {

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
if (indexPath.row == 0) {
    BOOL collapsed  = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
    for (int i = 0; i < [_questionArray count]; i++) {
        if (indexPath.section==i) {
            [arrayForBool removeObjectAtIndex:i];
            [arrayForBool insertObject:[NSString stringWithFormat:@"%d", !collapsed] atIndex:i];
        }
    }
    NSLog(@"%@", arrayForBool);
    [self.faqTblView reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    for (NSIndexPath *indexPath in self.faqTblView.indexPathsForSelectedRows) {
        [self.faqTblView deselectRowAtIndexPath:indexPath animated:NO];
         }
    cell1.imageView.transform = CGAffineTransformMakeRotation(M_PI);
     }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *questionCellIdentifier = @"questionCellIdentifier";
QuestionCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellIdentifier];
if (cell == nil) {
    NSArray * myNib;
    myNib =[[NSBundle mainBundle]loadNibNamed:@"QuestionCustomCell" owner:self options:nil];
    cell = (QuestionCustomCell *)[myNib lastObject];
}

BOOL manyCells  = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
if(manyCells){
    cell.questionNameLbl.text = [_answerArray objectAtIndex:indexPath.section];
}
return cell;
}

Ответ 12

Вы можете использовать ExpyTableView

Что делает расширяемый раздел из вашей ячейки. Совместимость с iOS 8.0. У вас будет гибкость, создавая расширяемое табличное представление с несколькими ячейками просмотра таблицы. Просто манипулируйте разделителями для состояний, и тогда никто не узнает, что вы используете несколько ячеек для расширения.

  • Другие решения:. Вы управляете высотой, чтобы развернуть ячейку, когда требуется обновление в дизайне ячейки, вам нужно будет перестроить все ограничения автоматической компоновки или логику в код.

  • ExpyTableView:. Вы создаете расширяемый вид таблицы, используя несколько ячеек и вставляя и удаляя их (что может означать расширение и сворачивание), у вас будет большая вероятность в будущих запросах на дизайн. Все, что вам нужно сделать, это добавить новый UITableViewCell и написать код для него. Вы легко получите новый дизайн.

Все, что вам нужно сделать, это import ExpyTableView, а затем:

class ViewController: ExpyTableViewDataSource, ExpyTableViewDelegate {

  @IBOutlet weak var expandableTableView: ExpyTableView!

  // First, set data source and delegate for your table view.
  override func viewDidLoad() {
    super.viewDidLoad() 
    expandableTableView.dataSource = self
    expandableTableView.delegate = self
  }

  // Then return your expandable cell instance from expandingCell data source method.
  func expandableCell(forSection section: Int, inTableView tableView: ExpyTableView) -> UITableViewCell {
    // this cell will be displayed at IndexPath with section: section and row 0
  }
} 

Вы можете видеть, что ваш прежний раздел представления таблиц теперь является секцией просмотра расширяемой таблицы. Вы также можете скачать примерный проект и посмотреть более подробные примеры.