如何让图片ScrollView始终居中当前选中索引(仿iPhone相机样式)
实现仿iPhone相机的图片滚动选择器(选中图片居中)
需求明确:打造一个横向滚动的图片选择视图,复刻iPhone相机图片查看器的核心交互——选中的图片始终处于屏幕中央。具体表现为:
- 选中第一张图时,它居中显示,右侧无其他图片
- 选中第N张图时,它居中,右侧保留N-1张图片(依此类推)
原代码的问题
原代码使用了scrollTargetLayout但未配置正确的滚动目标对齐逻辑,无法实现选中图片自动居中的效果。以下是修改后的完整实现:
struct ImagesScrollView: View { let selectedImages: [UIImage] @Binding var selectedImageIndex: Int @State private var scrollPosition: Int? var body: some View { ScrollView(.horizontal) { HStack(spacing: 8) { ForEach(0..<selectedImages.count, id: \.self) { index in Image(uiImage: selectedImages[index]) .resizable() .scaledToFill() .frame(width: index == selectedImageIndex ? 32 : 20, height: 30) .clipShape(RoundedRectangle(cornerRadius: 3)) .onTapGesture { selectedImageIndex = index scrollPosition = index } } } .scrollTargetLayout() } .scrollPosition(id: $scrollPosition) .scrollTargetBehavior(.viewAligned) .scrollTargetPadding(.horizontal, (UIScreen.main.bounds.width - 32) / 2) .padding(.bottom, 100) .onChange(of: selectedImageIndex) { newIndex in scrollPosition = newIndex } .onAppear { scrollPosition = selectedImageIndex } } }
关键修改说明
- 滚动位置绑定:新增
scrollPosition状态变量,通过scrollPosition(id:)与滚动视图绑定,实现选中图片时自动滚动到目标位置 - 滚动对齐行为:设置
scrollTargetBehavior(.viewAligned),确保滚动时目标图片精准对齐到指定位置 - 边缘适配:
scrollTargetPadding计算方式为(屏幕宽度 - 选中图片宽度)/2,保证第一张、最后一张图片也能居中显示 - 状态同步:通过
onChange监听选中索引变化,自动同步滚动位置;onAppear初始化时直接滚动到默认选中的图片 - 布局优化:统一设置HStack的
spacing,替代原有的条件式padding,让布局逻辑更清晰
内容的提问来源于stack exchange,提问作者john smith
相关产品推荐
相关产品推荐

