自定义布局中的sizeThatFits方法返回带有fixedSize修饰符的子视图的无效大小

问题描述 投票:0回答:1

我正在编写自定义 SwiftUI 布局并根据子尺寸计算容器高度。为了获取子视图的高度,我在下一个方法中使用

.sizeThatFits(.unspecified)

public func sizeThatFits(
    proposal: ProposedViewSize,
    subviews: Subviews,
    cache: inout ()
) -> CGSize {
    var totalHeight: CGFloat = 0

    let rows = computeRows(subviews: subviews, proposal: proposal)
    
    rows.forEach { cells in
        let sizes = cells.map { $0.sizeThatFits(.unspecified) }
        let maxViewHeight = sizes.map(\.height).max() ?? 0
        totalHeight += maxViewHeight
    }
    totalHeight += CGFloat(rows.count - 1) * spacing.height
    return CGSize(
        width: proposal.replacingUnspecifiedDimensions().width,
        height: totalHeight
    )
}

一切工作正常,直到我将

.fixedSize
修饰符添加到
Text
内部视图,这样它就不会截断文本。

Text(description)
    .font(.regular13)
    .foregroundStyle(Color.secondaryLabel)
    .lineLimit(nil)
    .fixedSize(horizontal: false, vertical: true)
    .multilineTextAlignment(.leading)

问题是

.sizeThatFits(.unspecified)
总是返回 121 的视图高度,但事实上,当我添加
fixedSize
修饰符时,它会变得更大(大约 136)。

swiftui swiftui-layout
1个回答
0
投票

您可以对此类视图使用 GeometryReader,以便成功加载视图并进行准确的测量。 像下面这样的东西应该可以解决问题。

GeometryReader { geometry in
        Text("Your text description goes here")
            .font(.system(size: 13))
            .foregroundColor(.secondary)
            .multilineTextAlignment(.leading)
            .frame(width: geometry.size.width, height: .infinity, alignment: .topLeading)
            .fixedSize(horizontal: false, vertical: true)
    }

如果您发现任何问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.