3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】スクロール可能な横に長いテキストの初期表示位置を右端にする!

Last updated at Posted at 2023-12-02

こんにちは。ymurao2です!

カテゴリを表示するときなど、スクロール可能な横に長い文字列を表示する際、初期表示位置を右端にしたいときがあると思います(例えば、以下のような画面)

参考

今回はこのようなViewをScrollViewを使って実装する方法を紹介します!

実装

var body: some View {
    HStack {
        Text("カテゴリ")
        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                Text("長いテキスト>長いテキスト>長いテキスト>長いテキスト>長いテキスト>")
                    .lineLimit(1)
                    .id("scroll")
            }
            .onAppear {
                proxy.scrollTo("scroll", anchor: .trailing)
            }
        }        
    }
}

ScrollViewReaderを使用し、onAppearでscrollToメソッドを呼ぶのがポイントです!

色など余分な情報はコード上から削除しています

こんな感じで初期表示位置を右端にできました!
IMG_0226.jpeg

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?