LoginSignup
12
9

More than 1 year has passed since last update.

【Swift】スクロールするとある位置に固定されるツールバー

Last updated at Posted at 2019-02-01

記事を移動しました。

https://zenn.dev/dd_sho/articles/0d630906e868cb
今後は上記の記事で更新します。(2021/10/03)

下図のように一定量スクロールすると固定されるツールバー(緑色のバー)を実装してみたので備忘録として記事にします。
実現する方法はたくさんあると思いますが個人的に一番楽なんじゃないかと思った方法です。

動作イメージ↓↓

スクロールツールバー.gif

開発環境

Xcode 10.0
Swift 4.2

実装イメージ

ソースコードはこちら(後でアップします)
実装イメージ.png

関連箇所の抜粋

以下は一定量スクロールすると固定されるツールバーの実装に関係する箇所の抜粋です。

①TableHeaderViewの設定

SampleViewController.swift
// viewDidLoadで下記のメソッドを呼ぶ
private func setupSampleHeaderView() {
    // 自作したtableHeaderView用のView
    sampleHeaderView.frame = CGRect(x: 0,
                                    y: 0,
                                    width: UIScreen.main.bounds.width,
                                    height: HEADER_HEIGHT)
    sampleTableView.tableHeaderView = sampleHeaderView
}

②SectionHeaderViewの設定

SampleViewController.swift
// MARK: - UITableViewDelegate
extension SampleViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let sectionView = SampleSectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 52))

        // sectionView内のボタンをタップした時の処理
        sectionView.tabButtonPressedBlock = {
            print("Did tap button")
        }
        return sectionView
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        // 適当な高さ
        return 52.0
    }
}

いつものTableViewの実装に加えて、①②を実装すれば実現できます。

まとめ

思っていたよりも簡単に実装できました。TableViewのsectionをツールバーとして見立てて実装する所がポイントかなぁと思います。
是非試してみてください。

12
9
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
12
9