【iOS小组件】可交互小组件

可交互小组件


注意:

  • 需要 iOS 17及以上版本

  • 可交互的组件仅支持 ButtonToggle 组件,其他控件不支持。

AppIntent意图

要想实现可点击交互的按钮需要继承 AppIntent 并实现对应的方法,AppIntentAppIntents 库中,需要先引入 import AppIntents

swift 复制代码
import AppIntents

// 全局存储结果
struct NumberManager {
    static var number = 0
}

struct MyCalculateIntent: AppIntent {
    // 标题
    static var title: LocalizedStringResource = "My Calculate Task"
    // 描述
    static var description: IntentDescription = IntentDescription("My Calculate Number Task")
    
    // 定义一个变量value
    @Parameter(title: "value")
    var value: Int
    
    init() { }
    init(value: Int) {
       self.value = value
    }
    
    // 计算结果,结果存储到全局
    func perform() async throws -> some IntentResult {
        NumberManager.number += value
        return .result()
    }
}

MyCalculateIntent 结构体遵守 AppIntent 协议并实现了对应的协议内容:titledescription ,并添加了一个 value 属性用来存储传入的数字,最后实现了 perform() 方法。

最终 MyCalculateIntent 会作用在可交互的按钮上,当点击按钮的时候就会调用 perform() 方法进行计算并将计算结果返回。

Widget

可交互小组件只支持 ButtonToggle , 点到组件我们可以看到在 iOS 17 上新增了支持传入 AppIntent 协议的初始化方法。

Widget代码

less 复制代码
struct MyWidgetMiddleEntryView : View {
    var entry: Provider.Entry
    
    var body: some View {
        VStack(spacing: 10) {
            HStack {
                 Text("Time:")
                 Text(entry.date, style: .time)
             }

            Text("结果: \(NumberManager.number)")
            
            HStack {
                Button(intent: MyCalculateIntent(value: 10)) {
                    Text("加 10")
                }
                Button(intent: MyCalculateIntent(value: 20)) {
                    Text("加 20")
                }
                Button(intent: MyCalculateIntent(value: -10)) {
                    Text("减 10")
                }
                Button(intent: MyCalculateIntent(value: -20)) {
                    Text("减 20")
                }
            }
            Text("中号组件类型")
        }
        .widgetBackground(Color.white)
    }
}
less 复制代码
struct MyWidgetMiddleEntryView : View {
    var entry: Provider.Entry
    @State var isOn: Bool = true
    
    var body: some View {
        VStack(spacing: 10) {
            HStack {
                 Text("Time:")
                 Text(entry.date, style: .time)
             }

            Text("结果: \(NumberManager.number)")
            
            HStack {
                Toggle(isOn: NumberManager.number % 2 == 0 ? false : true, intent: MyCalculateIntent(value: 1)) {
                    Text("状态发生改变加1");
                }.padding()
            }
        }
        .widgetBackground(Color.white)
    }
}

效果

最好运行看效果,预览模式可能不响应

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

相关推荐
kkoral4 小时前
基于MS-Swift 为 Qwen3-0.6B-Base 模型搭建可直接调用的 API 服务
python·conda·fastapi·swift
Yorelee.1 天前
ms-swift在训练时遇到的部分问题及解决方案
开发语言·nlp·transformer·swift
崽崽长肉肉2 天前
swift中的知识总结(一)
ios·swift
Yakamoz2 天前
Swift Array的写时复制
swift
汉秋2 天前
SwiftUI 中的 compositingGroup():真正含义与渲染原理
swiftui·swift
汉秋2 天前
SwiftUI 中的 @ViewBuilder 全面解析
swiftui·swift
胖虎13 天前
SwiftUI 页面作为一级页面数据被重置问题分析
ios·swiftui·swift·state·observedobject·stateobject·swiftui页面生命周期
guangzan3 天前
AI 结队编程:解决 SwiftUI 窗口点击关闭按钮崩溃问题
swiftui·tca
健了个平_243 天前
【iOS】如何在 iOS 26 的UITabBarController中使用自定义TabBar
ios·swift·wwdc
1024小神3 天前
xcode 配置了AppIcon 但是不显示icon图标
ios·swiftui·swift