首页 > 解决方案 > SwiftUI ScrollView 只向一个方向滚动

问题描述

尝试使用视图作为列表行样式创建自定义列表(默认情况下摆脱列表中丑陋的线分隔)。

但是,一旦我将 ZStack 行放在滚动视图中,滚动视图就会双向滚动,而不仅仅是垂直滚动。

这是内容视图:

NavigationView {
            ScrollView{
                VStack(alignment: .leading){
                    ForEach(friends) { friends in
                        NavigationButton(destination: MessageDetailView(friend: friends)) {
                            CustomListItem(friend: friends)
                        }
                    }
                    Spacer()
                }
            }
                .foregroundColor(.black)
                .navigationBarTitle(Text("Messages"))
        }

这是customListItem:

Group{
            ZStack {
                RoundedRectangle(cornerRadius: 10)
                    .shadow(radius: 1, y:1)
                    .frame(width: UIScreen.main.bounds.width - 32, height: 75)
                    .foregroundColor(.gray)

                HStack {
                    Image(systemName: "person.crop.circle")
                        .resizable()
                        .frame(width: 50, height: 50)
                    VStack(alignment: .leading) {
                        HStack {
                            Text(friend.name)
                                .font(.headline)
                            Text("\(friend.date, formatter: dateFormatter)")
                        }
                        Text(friend.messagesReceived[0])
                            .font(.subheadline)
                        }       .lineLimit(nil)
                    Spacer()
                    Image(systemName: "chevron.right.circle")
                        .foregroundColor(.black)
                    }.padding(10)
                }.padding([.leading, .trailing])
        }

有什么办法可以将滚动限制为垂直或在此强制框架?

尝试使用 .frame(...) 修饰符不起作用,因为我已经尝试过了。这导致视图根本不加载。

示例图像:

没有滚动视图

使用 ScrollView 包装 VStack

标签: swiftscrollviewswiftui

解决方案


从 Xcode 11 beta 3 (11M362v) 开始,axes在构造 a 时有一个参数ScrollView可以设置为.horizontal.vertical

ScrollView(.vertical, showsIndicators: true) { ... }

推荐阅读