【问题标题】:How to scroll scrollView so that TextField move above Keyboard in SwiftUI?如何滚动滚动视图以使 TextField 在 SwiftUI 中移动到键盘上方?
【发布时间】:2020-02-02 08:20:51
【问题描述】:

我设置了一个 UI,其中 ScrollView 中有 6 个字段,如下所示:

...
         ScrollView {

                IndicatorTextField(
                    index: 0,
                    hint: "Full Name",
                    icon: .imageUserBlue,
                    activeFieldTag: self.$activeFieldTag,
                    type: .alphabet
                ).padding(.top, 48)

                IndicatorTextField(
                    index: 1,
                    hint: "Email Address",
                    icon: .imageEmail,
                    activeFieldTag: self.$activeFieldTag,
                    type: .emailAddress
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 2,
                    hint: "Home Town",
                    icon: .imageLocation,
                    activeFieldTag: self.$activeFieldTag,
                    type: .alphabet
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 3,
                    hint: "Password",
                    icon: .imageLock,
                    activeFieldTag: self.$activeFieldTag,
                    indicatorColor: .reddishPink
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 4,
                    hint: "Date of Birth",
                    icon: .imageCalender,
                    activeFieldTag: self.$activeFieldTag,
                    type: .numbersAndPunctuation,
                    indicatorColor: .reddishPink
                ).padding(.top, 8)

                IndicatorTextField(
                    index: 5,
                    hint: "Gender",
                    icon: .imageUserRed,
                    activeFieldTag: self.$activeFieldTag,
                    indicatorColor: .reddishPink,
                    returnKey: .default
                ).padding(.top, 8)

                Spacer()
                    .frame(width: 0, height: -keyboardObserver.lastViewAdjustment)
            }
            .background(GeometryGetter(rect: $keyboardObserver.lastViewRect))
...

这里是keyboardObserver

当键盘出现时,我只需将Spacer 的高度更改为足以滚动到最后一个字段。

现在,我想自动滚动键盘上方的 firstResponder。

有人知道如何使用 SwiftUI 代码滚动 ScrollView 吗?

【问题讨论】:

    标签: ios swift swiftui swiftui-list


    【解决方案1】:

    到目前为止,我还没有找到在 SwiftUI 中滚动 ScrollView 的方法,但我使用了一种解决方法,我告诉父滚动视图从 UITextField 的包装器滚动:https://lostmoa.com/blog/ScrollTextFieldIntoVisibleRange/

    我发现它比包装 UIScrollView 更简单。

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多