1
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】ScrollViewを一番下から始める

Posted at

はじめに

チャット画面の実装する際にScrollViewを使うことになると思いますが、
開いた時は最新のチャットが表示されてないといけません。

最新のチャットは1番下にあるのでScrollViewを1番下からはじめたいです。

その方法を記録しておきます。

サンプルアプリ

Something went wrong

実装

ScrollView内の1番下の要素のidにproxy.scrollTo()で移動します

import SwiftUI

struct ContentView: View {
    var body: some View {
        ScrollView {
            ScrollViewReader { proxy in
                VStack(spacing: 10) {
                    ForEach(0..<50) { index in
                        RoundedRectangle(cornerRadius: 10)
                            .frame(maxWidth: .infinity)
                            .frame(height: 100)
                            .foregroundStyle(Color(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1)))
                            .id(index)
                    }
                }
                .padding(16)
                .onAppear {
                    proxy.scrollTo(49)
                }
            }
        }
    }
}

おわり

意外と簡単にできました

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