并非针对所有文本,而是针对特定文本长度,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))
}
}
结果是:
但应为:
如您在第一张图片中看到的,错误的第二行,但是在第二张图片中–错误的第三行(多行文字)
最佳答案
原因不是在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/