ios - GeometryReader使文本高度错误

标签 ios swift swiftui geometryreader

并非针对所有文本,而是针对特定文本长度,GeometryReader决定Text应该包含两行:

public var body: some View {
    ZStack {
        if loading {
            Text(text)
                .foregroundColor(.clear)
                .background(rectReader($frame))
                .fixedSize(horizontal: false, vertical: true) //Setting vertical to false - solve unwanted behaviour, but I can have multiline text and it makes multiline text single line, so I can't solve it by this way

            VStack {
                RoundedRectangle(cornerRadius: 8)
                    .frame(width: frame.width, height: 16)
                    .foregroundColor(.colorDivider)

                if frame.height > 24 {
                    RoundedRectangle(cornerRadius: 8)
                        .frame(width: frame.width, height: 16)
                        .foregroundColor(.colorDivider)
                }
            }
        } else {
            Text(text)
                .accessibility(identifier: accessibilityIdentifier)
                .fixedSize(horizontal: false, vertical: true)
        }
    }
    .background(Color.red)
}

func rectReader(_ binding: Binding<CGRect>) -> some View {
    return GeometryReader { geometry -> AnyView in
        let rect = geometry.frame(in: .global)
        DispatchQueue.main.async {
            binding.wrappedValue = rect
        }
        return AnyView(Rectangle().fill(Color.clear))
    }
}

结果是:

enter image description here

但应为:

enter image description here

如您在第一张图片中看到的,错误的第二行,但是在第二张图片中–错误的第三行(多行文字)

最佳答案

原因不是在Text中,而是在形状中。固定的变体是使用maxWidth而不是强宽度。经过Xcode 11.4 / iOS 13.4测试

RoundedRectangle(cornerRadius: 8).stroke(Color.gray)
    .frame(maxWidth: frame.width).frame(height: 16)

关于ios - GeometryReader使文本高度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61907939/

相关文章:

ios - 在 uiScrollView 之前添加 uiTextView

ios - UIPanGestureRecognizer 停留在状态 begin

iOS 框架不适用于模拟器

swift - 如何快速解析 Apache 日志文件?

ios - 在边界框内查询经/纬度的数据库/文件?谷歌地图

swift - 如何根据 SwiftUI 中的日期将事件分成列表的不同部分?

swift - 如何在 SwiftUI 中设置 addObserver?

ios - 取消正在进行的 CloudKit 查询

ios - 在结构类上查看为 var

ios - 属性 "Nonatomic"是什么意思?