ios iphone 中的可扩展 tableView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11626028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:24:51  来源:igfitidea点击:

Expandable tableView in iphone

iosiphonexcodeuitableview

提问by Rahul Patel

enter image description here

在此处输入图片说明

I want to make this type of expandable/collapsibletable view. there are categories and subcategories as in picture. for example "health and beauty" is a category and when i click this cell than its open subcategories as in picture below. So how can I make this type of table view? please suggest me.

我想使这个类型的展开/可折叠表视图。如图所示有类别和子类别。例如,“健康与美容”是一个类别,当我单击此单元格时,它会打开其打开的子类别,如下图所示。那么我怎样才能制作这种类型的表格视图呢?请建议我。

采纳答案by Rahul Patel

Finally i get two very useful helping link below which describes exact what the requirement is here Expanding/Collapsing TableView Sections
Collapsable Table View for iOS

最后,我在下面得到了两个非常有用的帮助链接,它们准确地描述了这里的要求 Expanding/Collapsing TableView Sections
Collapsable Table View for iOS

Really, good articles for such kind of expanding/collapsing tableview sections

真的,关于这种展开/折叠 tableview 部分的好文章

回答by Nimit Parekh

Use Following code for expandable Cell into UITableView

使用以下代码将可扩展单元格转换为 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;
}

code for expanding & collapsing rows – TableView DidSelectRow Method

用于展开和折叠行的代码 – TableView DidSelectRow 方法

- (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];
        }
    }
}

A Method which will help to minimize & maximize/expand-collapse rows.

一种有助于最小化和最大化/展开折叠行的方法。

-(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];
        }
    }
}

You can download the source code from my tutorial site.

您可以从我的教程站点下载源代码

回答by Maadiah

If this helps: [Access uitableview's expandable and collapsable sections] https://github.com/OliverLetterer/UIExpandableTableView

如果这有帮助:[访问 uitableview 的可扩展和可折叠部分] https://github.com/OliverLetterer/UIExpandableTableView

回答by kgaidis

I have a little bit of a different approach to expandable table views - one that aligns with how these kinds of table views are generally built.

我对可扩展表视图有一些不同的方法 - 一种与这些类型的表视图通常的构建方式一致的方法。

There are headersand there are cells. Headersshould be tappable, and then cellsunderneath the headers would show or hide. This can be achieved by adding a gesture recognizer to the header, and when tapped, you just remove all of the cells underneath that header (the section), and viceversa (add cells). Of course, you have to maintain state of which headers are "open" and which headers are "closed."

报头,并有细胞标题应该是可点击的,然后标题下方的单元格显示或隐藏。这可以通过向标题添加手势识别器来实现,当点击时,您只需删除该标题下方的所有单元格(部分),反之亦然(添加单元格)。当然,您必须维护哪些标头“打开”和哪些标头“关闭”的状态。

This is nice for a couple of reasons:

这很好,有几个原因:

  1. The job of headers and cells are separated which makes code cleaner.
  2. This method flows nicely with how table views are built (headers and cells) and, therefore, there isn't much magic - the code is simply removing or adding cells, and should be compatible with later versions of iOS.
  1. 标题和单元格的工作是分开的,这使代码更清晰。
  2. 这种方法与表格视图的构建方式(标题和单元格)很好地结合在一起,因此,没有太多魔法——代码只是删除或添加单元格,并且应该与更高版本的 iOS 兼容。

I made a very simple library to achieve this. As long as your table view is set up with UITableView section headers and cells, all you have to do is subclass the tableview and the header. Try it :)

我制作了一个非常简单的库来实现这一点。只要您的表格视图设置了 UITableView 部分标题和单元格,您所要做的就是对表格视图和标题进行子类化。尝试一下 :)

Link: https://github.com/fuzz-productions/FZAccordionTableView

链接:https: //github.com/fuzz-productions/FZAccordionTableView

enter image description here

在此处输入图片说明

回答by Vinay Kumar

Try Using this code... May be this can help.. And Feel free to Edit the code according to your requirements...

尝试使用此代码...可能会有所帮助...并且可以根据您的要求随意编辑代码...

#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 *Identifier=@"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

回答by Eyal

There is a great video in WWDC 2011 called UITableView Changes, Tips and Tricks - session 125that shows how to do things like this.
Also check out the example code TVAnimationsGestures

在 WWDC 2011 中有一个很棒的视频,叫做UITableView Changes, Tips and Tricks - session 125,展示了如何做这样的事情。
另请查看示例代码TVAnimationsGestures

回答by tadija

You may take a look at this accordion example in Swift: https://github.com/tadija/AEAccordion

您可以在 Swift 中查看这个手风琴示例:https: //github.com/tadija/AEAccordion

enter image description here

在此处输入图片说明

It's got very little code to create accordion effect (not by using sections but cells), and as a bonus there is also a solution to use XIB files inside other XIB files (useful for custom cells which use custom views).

创建手风琴效果的代码很少(不是使用节而是使用单元格),作为奖励,还有一个解决方案可以在其他 XIB 文件中使用 XIB 文件(对于使用自定义视图的自定义单元格很有用)。

回答by Varun

Please try this example :

请试试这个例子:

best example for Expandable TableView

可扩展 TableView 的最佳示例

https://github.com/OliverLetterer/UIExpandableTableView

https://github.com/OliverLetterer/UIExpandableTableView

回答by Timothy Moose

TLIndexPathToolscan do this sort of thing naturally. In fact, there is are extensions for both expandable sections and expandable tree structures. Try running the Collapsesample project for expandable sections and the Outline sample projectfor expandable trees.

TLIndexPathTools可以很自然地做这种事情。事实上,可扩展部分和可扩展树结构都有扩展。尝试运行可展开部分的折叠示例项目和可展开树的大纲示例项目

One advantage of using TLIndexPathTools is that, as a simple, low-level API, it can solve all kinds of dynamic table view and collection view problems using a common approach. And it works interchangeably with Core Data and plain arrays.

使用 TLIndexPathTools 的一个好处是,作为一个简单的低级 API,它可以使用通用的方法解决各种动态表视图和集合视图问题。它可以与 Core Data 和普通数组互换使用。

回答by Rahul

Check this Link :

检查此链接:

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

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

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

*Use UITableViewdelegate method viewForHeaderInSectionand return a custom UIView.

*使用UITableView委托方法viewForHeaderInSection并返回自定义 UIView。

*Add a UIButtonas subview with action "expandable:(id)sender" check the sender id as section number and reload the table view.

*添加一个UIButton带有操作“expandable:(id)sender”的子视图,检查发件人ID作为节号并重新加载表视图。