SwiftUI自定义标签栏如何实现手指拖拽划过按钮时切换视图?
SwiftUI 标签栏滑动拖拽激活实现方案
你可以通过 SwiftUI 原生的 PreferenceKey 配合拖拽手势实现需求,完全符合声明式设计规范,不需要手动做坐标命中测试的硬编码:
- 首先定义用于收集标签项布局信息的
PreferenceKey
struct TabItemFramePreference: PreferenceKey { static var defaultValue: [Int: CGRect] = [:] static func reduce(value: inout [Int: CGRect], nextValue: () -> [Int: CGRect]) { value.merge(nextValue()) { $1 } } }
- 给每个标签按钮添加布局信息上报修饰符,
index为当前标签对应的索引值
.background( GeometryReader { geo in Color.clear .preference(key: TabItemFramePreference.self, value: [index: geo.frame(in: .named("tabBar"))]) } )
- 给整个标签栏容器添加命名坐标空间,同时存储收集到的所有标签布局信息
@State private var tabFrames: [Int: CGRect] = [:] @State private var selectedTab = 0 // 标签栏父视图修饰符 .coordinateSpace(name: "tabBar") .onPreferenceChange(TabItemFramePreference.self) { tabFrames = $0 }
- 给标签栏添加全局同时识别的拖拽手势,匹配触摸点对应的标签
.simultaneousGesture( DragGesture(minimumDistance: 0) .onChanged { gesture in let touchPos = gesture.location guard let hitTab = tabFrames.first(where: { $0.value.contains(touchPos) })?.key else { return } selectedTab = hitTab } )
问题补充说明
你提到的 Playground 中出现的 AttributeGraph: cycle detected through attribute 提示是 SwiftUI Playground 本身的渲染缺陷,不属于代码逻辑问题,只要在正式 Xcode 项目中运行正常就无需额外处理。
内容的提问来源于stack exchange,提问作者Tomáš Kafka
相关产品推荐
相关产品推荐

