GeometryReader 使文本高度错误
GeometryReader make Text height wrong
不适用于所有文本,但对于特定长度的文本,GeometryReader 决定文本应包含两行:
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)
不适用于所有文本,但对于特定长度的文本,GeometryReader 决定文本应包含两行:
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)