LoginSignup
27
27

More than 5 years have passed since last update.

TwitterやAppStore風のSegement Control付きUITableViewを実装する

Last updated at Posted at 2015-01-24

Twitter公式アプリのプロフィール画面やAppStoreアプリの各アプリの画面のように、UITableViewでSectionのヘッダにSegment Controlを置いてテーブルの表示内容を切り替えるUIを実装したい場合があると思います。

  • AppStoreアプリ:

    1.png

  • Twitter公式iOSアプリ:

    2.png

UITableViewHeaderFooterViewを使って実装してみます。

実装

2番目のSectionの上部にSegment Controlを配置する例です。

  1. UITableViewとTopBarの間にUIViewをD&DしてSegment Controlを配置します。

    header.png

  2. UIView@IBOutletを作成します。

    code.png

    以下、UIViewの変数名をheaderViewとします。

  3. 2番目のsectionにUIViewを配置します。

    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        switch section {
        case 1:
            let sectionHeaderView = UITableViewHeaderFooterView()
            sectionHeaderView.contentView.addSubview(self.headerView)
            return sectionHeaderView
        default:
            return nil
        }
    }
    
  4. 2番目のsectionの高さを設定します。

    override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        switch section {
        case 1:
            return self.headerView.frame.height
        default:
            return 0
        }
    }
    
  5. ビルドして起動します。

    twitter.png

    背景を変えたい場合はUITableViewHeaderFooterViewのbackgroundViewを設定するなどします。

注意

SectionのヘッダのUITableViewCellに置くと次のような問題が発生します。

  1. Segment ControlでSegmentボタンをクリックする
  2. ネットワーク経由でデータを取得する
  3. reloadSectionやreloadDataでUITableViewCellを更新する
  4. Segment Controleの表示が初期状態に戻ってしまう←問題

UITableViewHeaderFooterViewを使えばこのような問題は発生しません。

27
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
27