iosswiftuiios14

Resolve: background(alignment:content:) is only available in iOS 15.0 or newer


I have the following to get the size of a View:

struct SizeKey : PreferenceKey
{
    static var defaultValue: CGSize = .zero

    static func reduce(value _: inout CGSize, nextValue _: () -> CGSize) {}
}

extension View
{
    func peekSize(_ size: Binding<CGSize>) -> some View
    {
        background   <=== ERROR
        {
            GeometryReader
            { geometry in
                Color.clear
                    .preference(key: SizeKey.self, value: geometry.size)
            }
        }
        .onPreferenceChange(SizeKey.self)
        { value in
            size.wrappedValue = value
        }
    }
}

which is used like so:

@State var textSize = CGSize.zero

    ...

    ScrollView
    {
        Text("The quick brown fox jumped over the lazy dog. How vexingly quick daft zebras jump! Pack my box with five dozen liquor jugs. ...")
            .peekSize($textSize)
    }
    .frame(maxHeight: textSize.height)

This is all fine on iOS 15+. But now I need to support iOS 14, which results in error background(alignment:content:) is only available in iOS 15.0 or newer.

Would you be willing to have a look and share how this can be resolved?


Solution

  • You should be able to use the background modifier that directly takes a View, instead of a @ViewBuilder closure. This is deprecated in iOS 17, but it is not deprecated in iOS 14.

    background( // notice the change to parentheses
        GeometryReader
        { geometry in
            Color.clear
                .preference(key: SizeKey.self, value: geometry.size)
        }
    )