主に備忘録

基本的には自分用の備忘録っぽいもの。

UITableViewでセクション毎に開閉(アコーディオン)を作ってみたかった。

今更ながらやってみました。

手順という程でも無いけど、
あえて分けるならこんな感じ。

  • セクションに設定するカスタムビュー作成
- (id)initWithTitle:(NSString *)title
       sectionIndex:(NSInteger)index
             isOpen:(BOOL)isOpen
{
    self = [super init];
    if (self) {
        [self setDefaultStyle];
        [self setTitle:title];
        [self setIndex:index];
        [self setOpenState:isOpen];
        [self switchArrowImg];
        [self addTapGesture];
    }
    return self;
}
  • カスタムビューにタップジェスチャーを追加
- (void)addTapGesture
{
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(sigleTapped)];
    [self addGestureRecognizer:singleTap];
}
  • セクションにカスタムビューを設定
/**
 セクションヘッダーのコンテンツを設定する
 */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.isHideSection) {
        return nil;
    }
    NSString *title = [sectionList_ objectAtIndex:section];
    BOOL isOpen = [self isEmptyList:sectionStateList_] ? YES : [[sectionStateList_ objectAtIndex:section] boolValue];
    CustomSectionHeaderView *containerView = [[CustomSectionHeaderView alloc] initWithTitle:title
                                                                               sectionIndex:section
                                                                                     isOpen:isOpen];
    containerView.delegate = self;
    
    return containerView;
}
  • カスタムビューのデリゲートを実装
/**
 シングルタップ時に実行される処理
 
 @param sectionIndex セクションのインデックス
 @param isOpen セクションの開閉状態
 */
- (void)didSectionHeaderSingleTap:(NSInteger)sectionIndex isOpen:(BOOL)isOpen
{
    [sectionStateList_ replaceObjectAtIndex:sectionIndex
                                 withObject:[NSNumber numberWithBool:isOpen]];
    [self.tableView beginUpdates];

    if (isOpen) {
        [self openSectionContents:sectionIndex];
    } else {
        [self closeSectionContents:sectionIndex];
    }
    
    [self.tableView endUpdates];
}

ソースはGitHubにあります。
https://github.com/negibouze/UITableViewAccordionSection

Markdown記法勉強しないと・・・。