SwiftUI实现Firebase图片横向滚动视图技术求助
实现横向滚动的Firebase图片展示视图
我明白你现在的困惑——从3×3网格切换到横向滚动视图,核心就是把原来的嵌套循环(行+列)改成单一的横向遍历,不用再拆分数组啦。下面我一步步帮你修改代码:
1. 简化ViewModel,移除数组拆分逻辑
原来的ProfileViewModel里的splitted数组是为了3列网格拆分用的,横向滚动不需要这个,直接用posts数组就行:
class ProfileViewModel: ObservableObject { @Published var posts: [Post] = [] @Published var isLoading = false func loadUserPosts(userId: String) { isLoading = true Api.User.loadPosts(userId: userId) { (posts) in self.isLoading = false self.posts = posts // 移除拆分数组的代码,直接用posts即可 } } }
2. 重构PhotoView为横向滚动布局
把原来的垂直ScrollView替换成横向的,直接遍历profileViewModel.posts数组生成图片项:
struct PhotoView: View { @Environment(\.presentationMode) var mode: Binding<PresentationMode> @EnvironmentObject var session: SessionStore @ObservedObject var profileViewModel = ProfileViewModel() var body: some View { ScrollView(.horizontal, showsIndicators: false) { if !profileViewModel.isLoading { HStack(spacing: 2) { // 控制图片之间的间距,和你的示例一致 ForEach(profileViewModel.posts, id: \.postId) { post in URLImage(URL(string: post.mediaUrl)!, content: { $0.image .resizable() .aspectRatio(contentMode: .fill) }) .frame(width: 100, height: 100) // 用你示例里的尺寸,可按需调整 .clipped() .cornerRadius(10) .shadow(radius: 4) } } .padding() // 给HStack加内边距,和示例对齐 } else { // 可以加个加载状态,比如ProgressView ProgressView() .frame(height: 100) } } .navigationBarTitle(Text("Photos"), displayMode: .inline) .navigationBarBackButtonHidden(true) .navigationBarItems(leading: Button(action : { self.mode.wrappedValue.dismiss() }) { Image(systemName: "arrow.left") }) .onAppear { self.profileViewModel.loadUserPosts(userId: Auth.auth().currentUser!.uid) } } }
关键修改点说明
- 横向滚动容器:用
ScrollView(.horizontal)替代原来的垂直ScrollView,showsIndicators: false可以隐藏滚动条,和你的示例一致。 - 遍历逻辑:直接用
ForEach(profileViewModel.posts, id: \.postId)遍历所有帖子,不需要再拆分行列,每个帖子对应一个图片项。 - 图片样式:沿用了你示例里的
frame(width: 100, height: 100)、cornerRadius(10)和shadow(radius: 4),保持视觉效果一致。 - 加载状态:新增了加载中的
ProgressView,提升用户体验,你也可以换成自定义的加载动画。
这样修改后,就能实现和你TestView示例一样的横向滚动效果,同时正确加载Firebase里的用户图片啦。
内容的提问来源于stack exchange,提问作者user3305606
相关产品推荐
相关产品推荐

