Using containerBackground with iOS16 deployment

Hi, I need to keep supporting iOS16 for my widgets. I'm having a problem using the iOS17 'containerBackground' API.

Ideally I would use a view extension:

extension View {
    func adoptableWidgetBackground(_ color: Color) -> some View {
        if #available(iOS 17.0, *) {
            containerBackground(for: .widget) { color }
        }
        else {
            background(color)
        }
    }
}

But this gives an error:

Branches have mismatching types 'some View' (result of 'Self.containerBackground(for:alignment:content:)') and 'some View' (result of 'Self.background(_:alignment:)')

If I try to use this directly on the 'body' view modifier like this:

if #available(iOS 17.0, *) {
            .containerBackground(for: .widget) {
                ContainerRelativeShape().fill(Color.init(UIColor.quaternarySystemFill))
            }
        } else {
            .background(ContainerRelativeShape().fill(Color.init(UIColor.quaternarySystemFill)))
        }

This doesn't work either.

Instance member 'containerBackground' cannot be used on type 'View'

How do I use this correctly?

Post not yet marked as solved Up vote post of zulfishah Down vote post of zulfishah
4.4k views

Replies

That seems like it should work. I am using a very similar form without problem and I am deploying back to iOS 15

extension View {
    func widgetBackground(_ color: Color) -> some View {
        if #available(iOSApplicationExtension 17.0, macOSApplicationExtension 14.0, *) {
            return  containerBackground(color, for: .widget)
        } else {
            return background(color)
        }
    }
}
  • Hmm, it wasn't working for me, until I added '@ViewBuilder' before the 'func'. Then it compiled for me, in Xcode 15 .

  • Do I use this right on a Zstack? When I use it it does nothing, I still get an error stating that I need to adopt to containerBackground API @jcgoforth @zulfishah

Add a Comment

when I implement this extension in my code using Xcode 15 beta 5, I get the following error: Type 'ContainerBackgroundPlacement' has no member 'widget' any ideas? should I open a radar?

I don't know the reason why but #available(iOSApplicationExtension 17.0, macOSApplicationExtension 14.0, *) doesn't work for me. Well, it sometimes works sometimes doesn't work. By 'Work' I mean the widgets get refreshed correctly.

I have to change it to

#available(iOS 17, macCatalyst 17, *)

And it works like a charm.

  • this api is

    @available(iOS 17.0, tvOS 17.0, macOS 14.0, watchOS 10.0, *)
        public func containerBackground
    
Add a Comment