【问题标题】:Scroll to very bottom of SwiftUI Scrollview when keyboard appears出现键盘时滚动到 SwiftUI Scrollview 的最底部
【发布时间】:2021-02-22 10:21:14
【问题描述】:

在我的 SwiftUI 项目中,我有以下布局

ScrollView {
    VStack {
        Text("some text that may change while editing the stuff below")
        TextField(...)
        TextField(...)
        Button(...)
    }
}

我想要实现的是,只要 TextField 获得焦点,ScrollView 就会滚动到最底部,即按钮可见。我尝试使用包装好的UIScrollView 和keyboardWillShow-notifications,但没有找到适用于iOS 13 和14 的任何东西。

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: swiftui scrollview


    【解决方案1】:

    你可以通过使用 ScrollViewReader 来实现,如果你不想要 onTapGesture,你可以使用keyboardWillShow-notifications

    ScrollView {
        ScrollViewReader { value in
            VStack {
                Text("some text that may change while editing the stuff below").id(0)
                TextField(...)
                    .id(1)
                    .onTapGesture {
                        withAnimation() {
                            value.scrollTo(3, anchor: .top) //or if you want the button in the center use .center
                        }
                     }
                TextField(...).id(2)
                Button(...).id(3)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 2015-02-02
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2018-12-08
      相关资源
      最近更新 更多