起動時とキーボード表示時に一番下までスクロール
swift
var body: some View {
ScrollViewReader { scrollView in
ScrollView {
LazyVStack {
...
EmptyView()
.frame(height: 0)
.id("bottom") // ★1 ダミー要素に "bottom" という id を降ってみた
}
}
.onAppear {
scrollToBottom(scrollView)
}
.task(priority: .background) {
await receiveNotificationKeyboardDidShow(scrollView)
}
}
}
func scrollToBottom(_ scrollView: ScrollViewProxy) {
scrollView.scrollTo("bottom")
}
func receiveNotificationKeyboardDidShow(_ scrollView: ScrollViewProxy) async {
let name = UIWindow.keyboardDidShowNotification
for await _ in NotificationCenter.default.notifications(named: name, object: nil) {
scrollToBottom(scrollView)
}
}