1

Not for all texts, but for specific length of text GeometryReader decides that Text should contains two lines:

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))
    }
}

As a result:

enter image description here

But should be:

enter image description here

As you can see in the first image wrong second line, but in the second image - wrong third line (multiline text)

Konstantin.Efimenko
  • 1,242
  • 1
  • 14
  • 38

1 Answers1

1

The reason is not in Text but in shapes. The fixed variant is to use maxWidth instead of strong width. Tested with Xcode 11.4 / iOS 13.4

RoundedRectangle(cornerRadius: 8).stroke(Color.gray)
    .frame(maxWidth: frame.width).frame(height: 16)
Asperi
  • 228,894
  • 20
  • 464
  • 690