我编写了一个解决方案,用某种占位符替换文本以更新数据。
例如从这样的:
我必须得到这样的:
但目前有解决方案:
public struct ShimmerText: View {
private var text: String
@Binding private var loading: Bool
@State private var frame = CGRect.zero
private var accessibilityIdentifier: String
public init(text: String,
loading: Binding<Bool>,
accessibilityIdentifier: String) {
self.text = text
self._loading = loading
self.accessibilityIdentifier = accessibilityIdentifier
}
public var body: some View {
ZStack {
if loading {
Text(text)
.foregroundColor(.clear)
.background(rectReader($frame))
.fixedSize(horizontal: false, vertical: true)
VStack {
RoundedRectangle(cornerRadius: 8)
.frame(maxWidth: frame.width)
.frame(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)
}
}
}
func rectReader(_ binding: Binding<CGRect>) -> some View {
return GeometryReader { geometry -> Color in
let rect = geometry.frame(in: .global)
DispatchQueue.main.async {
binding.wrappedValue = rect
}
return .clear
}
}
我只能得到:
您可以看到,最后两个占位符的行具有最大行的长度,但它应该重复每行的长度。文本也可能超过 3 行。
我想我需要在多行文本中找到每行文本的长度。