【iOS小组件】iOS17与低版本兼容适配

背景

当使用 XCode15.3 创建小组件时默认使用的都是最新语法和特性的示例模版,预览与运行一切正常。

当我们切换到低版本(如iOS14)后灾难出现了,代码一片红😢,即无法预览也无法运行😰。

前面【iOS小组件】第一个小组件 已经解决了,为了避免踩坑,这里描述一下遇到的错误与对应的兼容处理方案。

第一步:处理预览报错

预览示例中使用的 APIiOS17 开始支持的,当我们切换到低版本肯定会报错

🧰 处理方案就是改为低版本 API 写法。

定义一个 struct 继承自 PreviewProvider 并提供必要的 previewContext

css 复制代码
//#Preview(as: .systemSmall) {
//    MyWidget()
//} timeline: {
//    SimpleEntry(date: .now, emoji: "😀")
//    SimpleEntry(date: .now, emoji: "🤩")
//}

struct MyWidgetEntryView_Previews: PreviewProvider {
    static var previews: some View {
        MyWidgetEntryView(entry: SimpleEntry(date: Date(), emoji: "😁"))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}

重新预览,此时预览已正常,接下来处理 background 的兼容问题

第二步:处理背景兼容

从报错信息上可以看到,报错原因是因为没有使用 containerBackground

containerBackgroundiOS 17 中新增的接口,用于统一设置View背景颜色。如果你的小组件使用了 background 设置背景颜色,可能需要适配新的 containerBackground API

适配方法就是将 background 替换为containerBackground

  • 但要注意,containerBackground 仅在 iOS 17及以上版本 可用。

  • 如果小组件需要支持低版本,可以通过扩展的方式进行兼容处理。

兼容处理可以通过给 View 添加扩展方法解决:

swift 复制代码
extension View {
    // 背景
    @ViewBuilder
    func widgetBackground(_ backgroundView: some View) -> some View {
        // 如果是 iOS 17,则使用 containerBackground
        if #available(iOS 17.0, *) {
            containerBackground(for: .widget) {
                backgroundView
            }
        } else {
            background(backgroundView)
        }
    }
    
    func widgetBackground2(_ backgroundView: some View) -> some View {
        // 如果是 iOS 17,则使用 containerBackground
        if #available(iOS 17.0, *) {
            return containerBackground(for: .widget) {
                backgroundView
            }
        } else {
            return background(backgroundView)
        }
    }
}

上面提供了两种处理方式,第一种是通过 视图构造器 ,第二种是通过 扩展方法,使用哪种都行。

在设置背景颜色的时候就可以直接使用这个方法就行:

scss 复制代码
struct MyWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        VStack {
            Text("Time:")
            Text(entry.date, style: .time)

            Text("Emoji:")
            Text(entry.emoji)
        }
        // 设置背景
        .widgetBackground(Color.white)
    }
}

struct MyWidget: Widget {
    let kind: String = "MyWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
//            if #available(iOS 17.0, *) {
//                MyWidgetEntryView(entry: entry)
//                    .containerBackground(.fill.tertiary, for: .widget)
//            } else {
//                MyWidgetEntryView(entry: entry)
//                    .padding()
//            }
            
            // 新增加
            MyWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
    }
}

完整代码

swift 复制代码
extension View {
    // 背景
    @ViewBuilder
    func widgetBackground(_ backgroundView: some View) -> some View {
        // 如果是 iOS 17,则使用 containerBackground
        if #available(iOS 17.0, *) {
            containerBackground(for: .widget) {
                backgroundView
            }
        } else {
            background(backgroundView)
        }
    }
    
    func widgetBackground2(_ backgroundView: some View) -> some View {
        // 如果是 iOS 17,则使用 containerBackground
        if #available(iOS 17.0, *) {
            return containerBackground(for: .widget) {
                backgroundView
            }
        } else {
            return background(backgroundView)
        }
    }
}

struct MyWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        VStack {
            Text("Time:")
            Text(entry.date, style: .time)

            Text("Emoji:")
            Text(entry.emoji)
        }
        .widgetBackground(Color.white)
    }
}

struct MyWidget: Widget {
    let kind: String = "MyWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            // 新增加
            MyWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
    }
}

struct MyWidgetEntryView_Previews: PreviewProvider {
    static var previews: some View {
        MyWidgetEntryView(entry: SimpleEntry(date: Date(), emoji: "😁"))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
        MyWidgetEntryView(entry: SimpleEntry(date: Date(), emoji: "😁"))
            .previewContext(WidgetPreviewContext(family: .systemMedium))
    }
}

友情链接

Swift 官方教程:

developer.apple.com/swift

SwiftUI 官方教程:

developer.apple.com/tutorials/s...

本文同步自微信公众号 "程序员小溪" ,这里只是同步,想看及时消息请移步我的公众号,不定时更新我的学习经验。

相关推荐
初级代码游戏2 小时前
iOS开发 SwiftUI 14:ScrollView 滚动视图
ios·swiftui·swift
初级代码游戏5 小时前
iOS开发 SwitftUI 13:提示、弹窗、上下文菜单
ios·swiftui·swift·弹窗·消息框
zhyongrui7 小时前
托盘删除手势与引导体验修复:滚动冲突、画布消失动画、气泡边框
ios·性能优化·swiftui·swift
zhangfeng113310 小时前
CSDN星图 支持大模型微调 trl axolotl Unsloth 趋动云 LLaMA-Factory Unsloth ms-swift 模型训练
服务器·人工智能·swift
zhyongrui1 天前
SnipTrip 发热优化实战:从 60Hz 到 30Hz 的性能之旅
ios·swiftui·swift
大熊猫侯佩2 天前
Neo-Cupertino 档案:撕开 Actor 的伪装,回归 Non-Sendable 的暴力美学
swift·observable·actor·concurrency·sendable·nonsendable·data race
大熊猫侯佩2 天前
赛博深渊(上):用 Apple Foundation Models 提炼“禁忌知识”的求生指南
llm·swiftui·大语言模型·foundationmodel·apple ai·apple 人工智能·summarize
zhyongrui3 天前
SwiftUI 光晕动画性能优化:消除托盘缩放卡顿的实战方案
ios·性能优化·swiftui
2501_915921433 天前
在没有源码的前提下,怎么对 Swift 做混淆,IPA 混淆
android·开发语言·ios·小程序·uni-app·iphone·swift
00后程序员张4 天前
对比 Ipa Guard 与 Swift Shield 在 iOS 应用安全处理中的使用差异
android·开发语言·ios·小程序·uni-app·iphone·swift