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 / 问题 / 79447439
Accepted
Gargo
Gargo
Asked: 2025-02-18 15:30:12 +0800 CST2025-02-18 15:30:12 +0800 CST 2025-02-18 15:30:12 +0800 CST

向内部 HStack 元素添加相等的间距以填充 SwiftUI 中的可用空间?

  • 772

我从以下代码开始:

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack(spacing: 20) {
            ExtractedView(text: "Energy")
            ExtractedView(text: "Breath Control")
                
        }
        .padding(.horizontal, 20)
    }
}

#Preview {
    ContentView()
}

struct ExtractedView: View {
    let text: String
    
    var body: some View {
        Button {
            
        } label: {
            HStack(spacing: 8) {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundStyle(.tint)
                Text(text)
                    .lineLimit(1)
                    .font(.system(size: 18, weight: .bold))
            }
            .padding(.horizontal, 8)
            .padding(.vertical, 8)
            .background {
                Color.yellow
            }
        }
    }
}

在此处输入图片描述

我想要达到的大致结果: 在此处输入图片描述

换句话说,我需要在每个元素内的文本后添加相等的间距,但我不知道该怎么做。尝试了不同的代码,但按钮大小变得相等,或者 iOS 为第二个标签添加了换行符,或者即使有足够的空间也试图缩短第二个标签。

swiftui
  • 1 1 个回答
  • 61 Views

1 个回答

  • Voted
  1. Best Answer
    Benzy Neez
    2025-02-18T17:27:34+08:002025-02-18T17:27:34+08:00

    解决的一种方法是使用自定义Layout:

    • 理想的宽度取决于视图的理想尺寸。
    • 任何多余的宽度由容器中的各个视图平等共享。

    以下是一个按照这种方式工作的示例实现:

    struct PaddedToFill: Layout {
        typealias Cache = IdealSizes
        let spacing: CGFloat
    
        struct IdealSizes {
            let idealWidths: [CGFloat]
            let idealMaxHeight: CGFloat
    
            var isEmpty: Bool { idealWidths.isEmpty }
            var nWidths: Int { idealWidths.count }
        }
    
        func makeCache(subviews: Subviews) -> IdealSizes {
            var idealWidths = [CGFloat]()
            var idealMaxHeight = CGFloat.zero
            for subview in subviews {
                let idealViewSize = subview.sizeThatFits(.unspecified)
                idealWidths.append(idealViewSize.width)
                idealMaxHeight = max(idealMaxHeight, idealViewSize.height)
            }
            return IdealSizes(idealWidths: idealWidths, idealMaxHeight: idealMaxHeight)
        }
    
        func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout IdealSizes) -> CGSize {
    
            // Consume all the width available
            CGSize(width: proposal.width ?? 10, height: cache.idealMaxHeight)
        }
    
        func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout IdealSizes) {
            if !cache.isEmpty, subviews.count == cache.nWidths {
                let idealContainerWidth = cache.idealWidths.reduce(0) { $0 + $1 } + (CGFloat(cache.nWidths - 1) * spacing)
                let excessWidth = max(0, bounds.width - idealContainerWidth)
                let paddingPerView = excessWidth / CGFloat(cache.nWidths)
                var minX = bounds.minX
                for (index, subview) in subviews.enumerated() {
                    let w = cache.idealWidths[index] + paddingPerView
                    let viewSize = subview.sizeThatFits(ProposedViewSize(width: w, height: bounds.height))
                    let h = viewSize.height
                    let x = minX + ((w - viewSize.width) / 2)
                    let y = bounds.minY + ((bounds.height - h) / 2)
                    subview.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(width: w, height: h))
                    minX += w + spacing
                }
            }
        }
    }
    

    还需要对 进行更改,以便在添加黄色背景之前ExtractedView扩展以填充可用宽度:

    // ExtractedView
    
    Button {
    
    } label: {
        HStack(spacing: 8) {
            // ...
        }
        .padding(.horizontal, 8)
        .padding(.vertical, 8)
        .frame(maxWidth: .infinity) // 👈 added
        .background {
            Color.yellow
        }
    }
    

    要使用,只需将HStack原始代码替换为PaddedToFill:

    PaddedToFill(spacing: 20) {
        ExtractedView(text: "Energy")
        ExtractedView(text: "Breath Control")
    }
    .padding(.horizontal, 20)
    

    截屏


    在您的近似结果屏幕截图中,额外的填充始终位于每个按钮的尾部。要实现此结果,只需alignment在设置时maxWidth添加一个参数ExtractedView:

    HStack(spacing: 8) {
        // ...
    }
    .padding(.horizontal, 8)
    .padding(.vertical, 8)
    .frame(maxWidth: .infinity, alignment: .leading) // 👈 + alignment
    .background {
        Color.yellow
    }
    

    截屏


    EDIT Layout是在 iOS 16 中引入的。如果您仍需要支持 iOS 15,那么您将需要此版本的后备解决方案。一种方法是使用 测量容器的大小GeometryReader,然后在按钮之间共享多余的宽度。

    下面是一个如何用这种方式解决问题的例子。填充按钮的最简单方法是允许将额外填充的大小作为参数传递给ExtractedView:

    struct ExtractedView: View {
        let text: String
        var extraHorizontalPadding = CGFloat.zero // 👈 added
    
        var body: some View {
            Button {
    
            } label: {
                HStack(spacing: 8) {
                    // ...
                }
                .padding(.horizontal, 8)
                .padding(.horizontal, extraHorizontalPadding) // 👈 added
                .padding(.vertical, 8)
                .frame(maxWidth: .infinity)
                .background {
                    Color.yellow
                }
            }
        }
    }
    

    额外填充的尺寸的计算方式与自定义的计算方式相同Layout,基于容器的理想尺寸。

    • 通过将的隐藏版本添加HStack到背景并使用GeometryReader来测量其大小可以找到理想的大小。
    • 可用宽度是通过将可见部分HStack用另一个部分包裹来测量的GeometryReader。
    struct ContentView: View {
        let spacing: CGFloat = 20
        @State private var idealContainerSize: CGSize?
    
        @ViewBuilder
        private var buttons: some View {
            ExtractedView(text: "Energy")
            ExtractedView(text: "Breath Control")
        }
    
        var body: some View {
            if #available(iOS 16.0, *) {
                PaddedToFill(spacing: spacing) {
                    buttons
                }
                .padding(.horizontal, spacing)
            } else {
                legacyLayout
            }
        }
    
        private var legacyLayout: some View {
            GeometryReader { outer in
                let actualContainerWidth = outer.size.width
                let excessWidth: CGFloat = max(0, actualContainerWidth - (idealContainerSize?.width ?? actualContainerWidth))
                let paddingPerView = excessWidth / 2
                HStack(spacing: spacing) {
                    ExtractedView(text: "Energy", extraHorizontalPadding: paddingPerView / 2)
                        .fixedSize()
                    ExtractedView(text: "Breath Control", extraHorizontalPadding: paddingPerView / 2)
                        .fixedSize()
                }
                .frame(maxWidth: .infinity)
                .background {
                    HStack(spacing: spacing) {
                        buttons
                    }
                    .fixedSize()
                    .hidden()
                    .background {
                        GeometryReader { inner in
                            Color.clear
                                .onAppear {
                                    idealContainerSize = inner.size
                                }
                        }
                    }
                }
            }
            .frame(maxHeight: idealContainerSize?.height)
            .padding(.horizontal, spacing)
        }
    }
    
    @available(iOS 16.0, *)
    struct PaddedToFill: Layout {
        // ... as before
    }
    

    编辑 2Layout如果文本标签在一行上放不下时需要换行,则自定义会变得更加复杂。您可以尝试以下更改:

    1. 删除:.lineLimit​ExtractedView
    // ExtractedView
    
    Text(text)
        // .lineLimit(1)
        .font(.system(size: 18, weight: .bold))
    
    1. sizeThatFits如果建议宽度小于理想宽度,则将函数更改为请求两倍高度:
    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout IdealSizes) -> CGSize {
        let idealContainerWidth = cache.idealWidths.reduce(0) { $0 + $1 } + (CGFloat(cache.nWidths - 1) * spacing)
        let proposalWidth = proposal.width ?? 10
        return CGSize(
            width: proposalWidth,
            height: proposalWidth >= idealContainerWidth ? cache.idealMaxHeight : 2 * cache.idealMaxHeight
        )
    }
    

    这是实际需要的高度的一个相当粗略的近似值,它只允许文本换行到一行。更严格的实现需要调用具有减小宽度建议的子视图,其计算方式与 中完全相同placeSubviews。

    1. 允许多余的宽度为负placeSubviews
    // let excessWidth = max(0, bounds.width - idealContainerWidth)
    let excessWidth = bounds.width - idealContainerWidth
    
    • 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