问:如何在tableview中创建可扩展单元格(通过单击单元格应在特定部分的特定行展开和折叠),请帮助我。
提前致谢
答:
我们可以通过使用表视图中的部分轻松地做到这一点。向节标题添加按钮或点击手势,并使用以下代码处理该动作:
打开:
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
关闭:
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
其中“ indexPathsToInsert”和“ indexPathsToDelete”是NSIndexPath对象的数组。
NSMutableArray * indexPathsToInsert = @ [[[NSIndexPath indexPathForRow:0 inSection:0]];
NSMutableArray * indexPathsToDelete = @ [[[NSIndexPath indexPathForRow:0 inSection:0]];
同样,当我们关闭该节时,我们需要将“ numberOfRowsInSection”返回零,而在打开该节时,需要返回“所需的行数”。
以下是显示和隐藏单行的一个小示例。
@interface DemoViewController()<UITableViewDelegate,UITableViewDataSource>
{
BOOL是OpenFlag;
}
@属性(非原子的,弱的)IBOutlet UITableView * tableView;
@结束
@implementation DemoViewController
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0){
返回isOpenFlag?1:0;
}其他{
返回2;
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
返回2;
}
-(void)closeSection {
NSArray * indexPathsToDelete = @ [[[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
}
-(void)openSection {
NSArray * indexPathsToInsert = @ [[[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@“ cell” forIndexPath:indexPath];
[cell.textLabel setText:[NSString stringWithFormat:@“ Cell%d”,indexPath.row]];
返回单元
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UITableViewCell * header = [tableView dequeueReusableCellWithIdentifier:@“ cell”];
如果(section == 0){
[header addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSection)]]];
header.textLabel.text = @“点击打开”;
}其他{
header.textLabel.text = @“ NextSection”;
}
UIView * view = [[UIView alloc] initWithFrame:[标题框架]];
header.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[view addSubview:header];
返回视图
}
-(void)tapSection {
isOpenFlag =!isOpenFlag;
如果(!isOpenFlag){
[self closeSection];
}其他{
[self openSection];
}
}