AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79541601
Accepted
Deepak Sharma
Deepak Sharma
Asked: 2025-03-28 21:44:13 +0800 CST2025-03-28 21:44:13 +0800 CST 2025-03-28 21:44:13 +0800 CST

SwiftUI 离散洗涤器实现

  • 772

我正在尝试在 SwiftUI 中实现带有文本标记的离散洗涤器,如下所示。我的问题是我无法确定先验HStack内部的高度ScrollView,因此我尝试使用onGeometryChange修饰符,但它不起作用(即覆盖文本被截断)。一种解决方法是使用并根据几何代理GeometryReader分配高度,但我想知道是否有另一种不使用的方法。HStackGeometryReader

struct ScrollScrubber: View {
    var config:ScrubberConfig
    
    @State var viewSize:CGSize?
    
    var body: some View {
        let horizontalPadding = (viewSize?.width ?? 0)/2
        
        ScrollView(.horizontal) {
            HStack(spacing:config.spacing) {
                let totalSteps = config.steps * config.count
                
                ForEach(0...totalSteps, id: \.self) { index in
                    let remainder = index % config.steps
                    Divider()
                        .background( remainder == 0 ? Color.primary : Color.gray)
                        .frame(width: 0, height: remainder == 0 ? 20 : 10, alignment: .center)
                        .frame(maxHeight: 20, alignment: .bottom)
                        .overlay(alignment: .bottom) {
                            if remainder == 0 {
                                Text("\(index / config.steps)")
                                    .font(.caption)
                                    .fontWeight(.semibold)
                                    .textScale(.secondary)
                                    .fixedSize()
                                    .offset(y:20)
                            }
                        }
                    
                }
            }
            .frame(height:viewSize?.height)
            
        }
        .scrollIndicators(.hidden)
        .safeAreaPadding(.horizontal, horizontalPadding)
        .onGeometryChange(for: CGSize.self) { proxy in
            proxy.size
        } action: { newValue in
            viewSize = newValue
            print("View Size \(newValue)")
        }


    }
}

struct ScrubberConfig:Equatable {
    var count:Int
    var steps:Int
    var spacing:CGFloat
}

#Preview {
    ScrollScrubber(config: .init(count: 100, steps: 5, spacing: 5.0))
        .frame(height:60)
}


swiftui
  • 1 1 个回答
  • 32 Views

1 个回答

  • Voted
  1. Best Answer
    Sweeper
    2025-03-29T08:26:58+08:002025-03-29T08:26:58+08:00

    如果您确实希望滚动视图的高度占据所有可用空间,那么GeometryReader在这里使用是完全合适的。这没有什么错。否则,您必须使用其他填充可用空间的视图(例如Color.clear),并测量该视图的几何形状。

    Color.clear
        .onGeometryChange(for: CGSize.self) { proxy in
            proxy.size
        } action: { newValue in
            viewSize = newValue
        }
        .overlay {
            ScrollView { ... } // the actual scroll view would go on an overlay
                .frame(height: viewSize?.height)
        }
    

    显然,只使用 aGeometryReader更方便。


    在这个特殊情况下,如果您只想阻止Texts 被剪切,您可以通过放置滚动视图来禁用剪切scrollClipDisabled()。无需执行任何与几何相关的操作,您可以删除frame滚动视图上的 。

    请注意,Texts 仍将在 的边界之外ScrollView。如果您希望它们在边界内,请考虑使用 来VStack布局刻度线和文本:

    ForEach(0...totalSteps, id: \.self) { index in
        let remainder = index % config.steps
        VStack {
            Rectangle() // changed the Divider to a Rectangle, because a Divider is horizontal in a VStack
                .fill( remainder == 0 ? Color.primary : Color.gray)
                .frame(width: 1, height: remainder == 0 ? 20 : 10, alignment: .center)
                .frame(maxHeight: 20, alignment: .bottom)
            Text("\(index / config.steps)")
                .font(.caption)
                .fontWeight(.semibold)
                .textScale(.secondary)
                .fixedSize()
                .opacity(remainder == 0 ? 1 : 0)
        }
    }
    

    这假设所有文本都具有相同的高度。如果您不能假设这一点,您可以Text使用首选项键找到所有 s 的最大高度。然后,将 的高度设置HStack为文本的最大高度加上分隔符的最大高度(即 20)。

    struct MaxHeightPreference: PreferenceKey {
        static let defaultValue: CGFloat = 0
        
        // this reduce implementation finds the maximum height of all the sibling views
        static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
            value = max(value, nextValue())
        }
    }
    
    struct MaxHeightPreferenceModifier: ViewModifier {
        @State private var height: CGFloat = 0
    
        func body(content: Content) -> some View {
            content
                .onGeometryChange(for: CGFloat.self, of: \.size.height) { newValue in
                    height = newValue
                }
                .preference(key: MaxHeightPreference.self, value: height)
        }
    }
    
    struct ScrollScrubber: View {
        var config:ScrubberConfig
        
        @State var viewWidth: CGFloat = 0
        @State var maxTextHeight: CGFloat = 0
        
        var body: some View {
            let horizontalPadding = viewWidth / 2
            
            ScrollView(.horizontal) {
                HStack(spacing:config.spacing) {
                    let totalSteps = config.steps * config.count
                    ForEach(0...totalSteps, id: \.self) { index in
                        let remainder = index % config.steps
                        Divider()
                            .background( remainder == 0 ? Color.primary : Color.gray)
                            .frame(width: 0, height: remainder == 0 ? 20 : 10)
                            .frame(maxHeight: 20, alignment: .bottom)
                            // the text should align to the top of the divider, so that
                            // .offset(y:20) will put the text directly under the divider
                            .overlay(alignment: .top) {
                                if remainder == 0 {
                                    Text("\(index / config.steps)")
                                        .font(.caption)
                                        .fontWeight(.semibold)
                                        .textScale(.secondary)
                                        .fixedSize()
                                        .modifier(MaxHeightPreferenceModifier())
                                        .offset(y:20)
                                }
                            }
                    }
                }
                .frame(height: maxTextHeight + 20, alignment: .top)
            }
            .scrollIndicators(.hidden)
            .safeAreaPadding(.horizontal, horizontalPadding)
            .onGeometryChange(for: CGFloat.self, of: \.size.width) { newValue in
                viewWidth = newValue
            }
            .onPreferenceChange(MaxHeightPreference.self) { newValue in
                maxTextHeight = newValue
            }
            // this border is to show the bounds of the ScrollView.
            // you can see that it does not take up all the available height,
            // only as much height as needed by the dividers + texts
            .border(.red)
        }
    }
    
    • 1

相关问题

  • SwiftUI:如何创建颜色较浅的渐变?

  • SwiftUI - 带有“绑定”变量的通用视图

  • 创建日历日视图

  • 如何让 SwiftUI 的动画变慢

  • 不理解 SwiftUI 文本布局

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve