如何在 SwiftUI 中滚动滚动视图以使 TextField 移动到键盘上方?

And*_*per 5 ios swift swiftui swiftui-list

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

...
         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))
...
Run Code Online (Sandbox Code Playgroud)

这是键盘观察者

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

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

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

小智 1

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

我发现这是比包装更简单的解决方案UIScrollView