TableView的cell折疊和展開

基本原理就是利用section的和row的關(guān)系车荔,當(dāng)點擊section的頭部view時候渡冻,就刷新下列表,展開當(dāng)前section下的row忧便,效果圖如下:

折疊.gif
  • 關(guān)鍵代碼
//
//  ViewController.m
//  TableView的折疊收起
//
//  Created by liyang on 16/6/15.
//  Copyright ? 2016年 liyang. All rights reserved.
//

#import "ViewController.h"

#import "LYTableViewCell.h"
#import "LYHeaderView.h"

#import "LYSectionItem.h"
#import "LYCellItem.h"

static NSString *const cellIdentifier = @"frinedCell";

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, HeaderViewDelegate>
@property(nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;
@end

@implementation ViewController

- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] init];
        tableView.frame = self.view.bounds;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
        tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0);
        [self.view addSubview:tableView];
        self.tableView = tableView;
    }
    return _tableView;
}

// 懶加載
- (NSArray *)dataArray
{
    if (!_dataArray) {
        
        NSArray *arr = @[ @{
                           @"sectionName":@"sectionName1",
                           @"cellItems":@[
                                   @{@"cellItemName":@"cellName1"},
                                   @{@"cellItemName":@"cellName2"},
                                   @{@"cellItemName":@"cellName3"}
                                   ]
                           },
                        @{
                          @"sectionName":@"sectionName2",
                          @"cellItems"  :@[
                                  @{@"cellItemName":@"cellName1"},
                                  @{@"cellItemName":@"cellName2"},
                                  @{@"cellItemName":@"cellName3"}
                                  ]
                          },
                        @{
                          @"sectionName":@"sectionName3",
                          @"cellItems":@[
                                  @{@"cellItemName":@"cellName1"},
                                  @{@"cellItemName":@"cellName2"},
                                  @{@"cellItemName":@"cellName3"}
                                  ]
                          }];
        NSMutableArray *tempArr = [NSMutableArray array];
        for (int i = 0; i < 6; i++) {
            for (NSDictionary *dic in arr) {
                LYSectionItem *model = [LYSectionItem sectionItemWithDic:dic];
                [tempArr addObject:model];
            }
        }
        self.dataArray = tempArr;
        
        [self.tableView reloadData];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     [self.tableView registerClass:[LYTableViewCell class] forCellReuseIdentifier:cellIdentifier];
    [self dataArray];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    LYSectionItem *sectionItem = self.dataArray[section];
    // 條件表達式族吻。得出row行數(shù)
    return sectionItem.isOpen ? sectionItem.cellItems.count : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LYTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    LYSectionItem *sectionItem = self.dataArray[indexPath.section];
    LYCellItem *cellItem = sectionItem.cellItems[indexPath.row];
    
    cell.cellItem = cellItem;
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LYSectionItem *sectionItem = self.dataArray[indexPath.section];
    LYCellItem *cellItem = sectionItem.cellItems[indexPath.row];
    return cellItem.cellHeight;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    LYSectionItem *sectionItem = self.dataArray[section];
    LYHeaderView *header = [LYHeaderView headerView:tableView];
    header.delegate = self;
    header.sectionItem = sectionItem;
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
#pragma mark - HeaderViewDelegate
- (void)headerViewClick:(LYHeaderView *)headerView
{
    // 改變了isopen的值
    [self.tableView reloadData];//刷新列表
}

@end
  • 自定義了一個TableView的頭視圖,當(dāng)點擊它的時候珠增,通過控制模型isOpen屬性來達到控制列表是否展開
//
//  LYHeaderView.m
//  TableView的折疊收起
//
//  Created by liyang on 16/6/15.
//  Copyright ? 2016年 liyang. All rights reserved.
//

#import "LYHeaderView.h"
#import "LYSectionItem.h"

@interface LYHeaderView ()
@property (nonatomic, strong) UIButton *arrowBtn;
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation LYHeaderView

+ (instancetype)headerView:(UITableView *)tableView
{
    static NSString *kHeadIdentifier = @"header";
    LYHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeadIdentifier];
    if (!headerView) {
        headerView = [[self alloc] initWithReuseIdentifier:kHeadIdentifier];
    }
    return headerView;
}

- (UIButton *)arrowBtn
{
    if (!_arrowBtn) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"buddy_header_arrow"] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        // 距離
        button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        //內(nèi)容的水平對齊方式
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        button.imageView.contentMode = UIViewContentModeCenter;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        //不裁剪圖片
        button.imageView.clipsToBounds = NO;
        [self addSubview:button];
        self.arrowBtn = button;
    }
    return _arrowBtn;
}
- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        UILabel *labelRight = [[UILabel alloc] init];
        labelRight.textAlignment = NSTextAlignmentCenter;
        [self addSubview:labelRight];
        self.titleLabel = labelRight;
    }
    return _titleLabel;
}

- (void)setSectionItem:(LYSectionItem *)sectionItem
{
    _sectionItem = sectionItem;
    
    [self.arrowBtn setTitle:sectionItem.name forState:UIControlStateNormal];
    self.titleLabel.text = [NSString stringWithFormat:@"%ld", sectionItem.cellItems.count];
    
    // 添加觀察者呼奢,觀察isOpen屬性的變化,來調(diào)節(jié)指示器的狀態(tài)
    [self addObserver:self forKeyPath:@"sectionItem.isOpen" options:NSKeyValueObservingOptionInitial context:nil];
}

- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
{
    // 改變button圖片的旋轉(zhuǎn)讀
    self.arrowBtn.imageView.transform = self.sectionItem.isOpen ? CGAffineTransformMakeRotation(M_PI_2) : CGAffineTransformMakeRotation(0);
}

//布局
- (void)layoutSubviews {
    [super layoutSubviews];
    self.arrowBtn.frame = self.bounds;
    self.titleLabel.frame = CGRectMake(self.bounds.size.width - 70, 0, 60, self.frame.size.height);
}

#pragma mark - buttonAction
- (void)buttonAction:(UIButton *)sender {
    //修改groupModel的isOpen屬性
    self.sectionItem.isOpen = !self.sectionItem.isOpen;
    if ([self.delegate respondsToSelector:@selector(headerViewClick:)]) {
        [self.delegate headerViewClick:self];
    }
}
@end
  • 主要就是練習(xí)模型控制View

[GitHub地址][1]
[1]:https://github.com/liyang123/TableView-.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末切平,一起剝皮案震驚了整個濱河市握础,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌悴品,老刑警劉巖禀综,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異苔严,居然都是意外死亡定枷,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進店門届氢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來欠窒,“玉大人,你說我怎么就攤上這事退子♂” “怎么了?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵寂祥,是天一觀的道長荐虐。 經(jīng)常有香客問我,道長丸凭,這世上最難降的妖魔是什么福扬? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任腕铸,我火速辦了婚禮,結(jié)果婚禮上铛碑,老公的妹妹穿的比我還像新娘狠裹。我一直安慰自己,他們只是感情好汽烦,可當(dāng)我...
    茶點故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布酪耳。 她就那樣靜靜地躺著,像睡著了一般刹缝。 火紅的嫁衣襯著肌膚如雪碗暗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天梢夯,我揣著相機與錄音言疗,去河邊找鬼。 笑死颂砸,一個胖子當(dāng)著我的面吹牛噪奄,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播人乓,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼勤篮,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了色罚?” 一聲冷哼從身側(cè)響起碰缔,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎戳护,沒想到半個月后金抡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡腌且,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年梗肝,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片铺董。...
    茶點故事閱讀 39,773評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡巫击,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出精续,到底是詐尸還是另有隱情坝锰,我是刑警寧澤,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布驻右,位于F島的核電站什黑,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏堪夭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望森爽。 院中可真熱鬧恨豁,春花似錦、人聲如沸爬迟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽付呕。三九已至计福,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間徽职,已是汗流浹背象颖。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留姆钉,地道東北人说订。 一個月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像潮瓶,于是被迫代替她去往敵國和親陶冷。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,689評論 2 354

推薦閱讀更多精彩內(nèi)容