首页 > 解决方案 > 如何滚动到 ScrollView 中的选定项目?(斯威夫特用户界面)

问题描述

我看到我们可以滚动到 ScrollView 中的任何项目,这要归功于 iOS 14 和 Xcode 12 的 ScrollViewReader 功能,但我想要在 iOS 13 和 Xcode 11 上做同样的事情。

我有一个消息页面,顶部是联系人,下面是消息列表。我希望当用户选择一个联系人时,scrollView 必须滚动到该选定项目。当我选择任何未显示屏幕的联系人(例如:最后一个)时,scrollView 会返回第一项。我不想要那种行为。

通过下面的屏幕截图,您可以理解我的意思。

消息页面截图

滚动视图:

ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 15){
                    ForEach(self.viewModel.contacts.indices, id: \.self){ index in
                        Button(action: {
                            self.selectedUser = index
                            self.viewModel.selectedUser = self.viewModel.contacts[index].user!.id
                            self.viewModel.loadMoreMessages()
                        }) {
                                ZStack(alignment: .topLeading) {
                                    KFImage(URL(string: self.viewModel.contacts[index].user!.avatar!.userAvatarPathSmall()))
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                                        .animation(.easeInOut(duration: 0.5))
                                        .frame(width: 52, height: 52)
                                        .cornerRadius(26)
                                    if self.viewModel.contacts[index].unread! > 0 {
                                        ZStack {
                                            Circle()
                                                .foregroundColor(.red)
                                            Text("\(self.viewModel.contacts[index].unread!)")
                                                .foregroundColor(.white)
                                                .font(Font.system(size: 12))
                                        }.frame(width: 20, height: 20)
                                    } else {
                                        EmptyView()
                                    }
                                }.contextMenu {
                                    Button(action: {
                                    }) {
                                        Text(self.viewModel.contacts[index].user!.name!)
                                    }
                                    
                                    Button(action: {
                                    }) {
                                        Text("@\(self.viewModel.contacts[index].user!.username!)")
                                    }
                                }
                        }.buttonStyle(PlainButtonStyle())
                    }
                }.padding(.horizontal, 20)
            }.id(UUID().uuidString).frame(height: 76)

标签: iosswiftui

解决方案


推荐阅读