iOS開發之模仿qq通訊錄

這篇文章主要整理一下項目中用到的類似qq通訊錄的收縮功能。

demo.gif

我實現的思路是在tableview的header放置button,然后根據button是否選中來判斷是否需要顯示那一個section。

首先定義了兩個屬性

@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSArray *buttonsArr;

button數組的定義

-(NSArray *)buttonsArr{
    
    if (_buttonsArr==nil) {
        
        NSMutableArray *tmp=[NSMutableArray array];
        
        for (int i=0; i<6; i++) {
            
            UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
            button.tag=333+i;
            button.backgroundColor=[UIColor redColor];
            [button setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
            button.selected=NO;
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            [tmp addObject:button];
        }
        _buttonsArr=[NSArray arrayWithArray:tmp];
    }
    return _buttonsArr;
}

按鈕的點擊方法,根據按鈕的選中狀態刷新tableview

-(void)buttonAction:(UIButton *)button{
    
    button.selected=!button.isSelected;
    
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:button.tag-333] withRowAnimation:UITableViewRowAnimationFade];
}

tableview的一系列代理方法

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    UIButton *button=self.buttonsArr[section];
    
    if (button.selected==YES) {
        return 1;
    }else{
        return 0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str=@"cellid";
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        cell.textLabel.text=[NSString stringWithFormat:@"第%li節",indexPath.section];
    }
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIButton *button=self.buttonsArr[section];
    
    return button;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 150;
}

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

源碼

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容