LoginSignup
1
1

More than 1 year has passed since last update.

【SwiftUI】ScrollView内にViewが追加されるとき、最下部まで自動スクロールする

Posted at

問題

ForEachを持つScrollView内で、Viewが追加されるたびに、最下部へ自動スクロールしてほしいと思いました。この記事はその備忘録として残します。

解決策

ScrollViewReader { proxy in
    ScrollView {
        ForEach(array, id: \.self) {string in
            Text(string)
        }
        Color.clear.id(array.count)
    }
    .onChange(of: array) { _ in
        withAnimation {
            proxy.scrollTo(array.count)
        }
    }
}

ScrollViewReader内でScrollViewを宣言し、arrayの変化に応じてColor.clearまでスクロールさせます。

動作イメージ

開発環境

  • Xcode 14.2
  • iOS 16 and later

参考URL

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