0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

初期選択可能なスクロールタブを作る

Posted at

はじめに

今回はSwiftUIを使って良くある初期選択が可能なスクロールタブを実装していきます

コード

// 該当位置までスクロールさせるにはScrollViewReaderが必要
ScrollViewReader { scroll in
    ScrollView(.horizontal, showsIndicators: false) {
        HStack(spacing: 8) {
            ForEach(0..<viewModel.tabs.count, id: \.self) { index in
                let tab = viewModel.tabs[index]
                segmentItem(title: tab.title, isSelected: viewModel.isSelected(index: index))
                    .id(index)
                    .onTapGesture {
                        // タップ処理
                    }
                    .padding(.horizontal)
                }
                // 生成時に選択済みの箇所までスクロールさせる
                // anchorはどこまでスクロールさせるかの選択
                .onAppear {
                    scroll.scrollTo(viewModel.selectedIndex, anchor: .leading)
                }
            }

最後に

意外と使う機会が多いので、備忘録的に残してみました
どなたかのお役に立てれば幸いです

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?