美文网首页
SwiftUI Widget IntentConfigurati

SwiftUI Widget IntentConfigurati

作者: iOS_July | 来源:发表于2021-04-15 14:56 被阅读0次

    首先,Widget 分为StaticConfigurationIntentConfiguration,一个静态、长按不可编辑,一个是长按可编辑

    这里要讲的是IntentConfiguration

    • 创建widget时,勾选Intent
    • 创建widget时,不勾选Intent,直接在后期手动撸
      ps: 前者没什么讲的,直接撸怎么在后期 手动撸一个IntentConfiguration

    一、创建Intent文件

    • New File 选择 Siri Intent Definition File,在创建的时候,要注意Targets的勾选,要给谁用,就要勾选谁,不只是项目Target,还要勾选对应的小组件Target

    • 添加Intents,命名最好跟刚创建的 Siri Intent Definition File文件一致,便于记忆和读

      intent

    二、修改默认代码

    • 先修改Widget的配置,StaticConfiguration改成IntentConfiguration
    @main
    struct XG_Widget: Widget {
        let kind: String = "XG_Widget"
    
        var body: some WidgetConfiguration {
            IntentConfiguration(kind: kind, intent: MyCustomIntentsIntent.self, provider: Provider()) { entry in
                XG_WidgetEntryView(entry: entry)
            }
            .configurationDisplayName("XG_SwiftUI_3Day")
            .description("这是一个测试的widget.")
        }
    }
    
    

    同理修改其他代码为:

    
    struct Provider: IntentTimelineProvider {
        typealias Entry = SimpleEntry
        
        typealias Intent = MyCustomIntentsIntent
        
        
        func placeholder(in context: Context) -> SimpleEntry {
            SimpleEntry(date: Date())
        }
    
        func getSnapshot(for configuration: Intent, in context: Context, completion: @escaping (SimpleEntry) -> Void) {
            let entry = SimpleEntry(date: Date())
            completion(entry)
        }
    
        func getTimeline(for configuration: Intent, in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) {
            var entries: [SimpleEntry] = []
    
            // Generate a timeline consisting of five entries an hour apart, starting from the current date.
            let currentDate = Date()
            for hourOffset in 0 ..< 5 {
                let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
                let entry = SimpleEntry(date: entryDate)
                entries.append(entry)
            }
    
            let timeline = Timeline(entries: entries, policy: .atEnd)
            completion(timeline)
        }
    }
    

    至此,添加小组件后,长按会出现可编辑按钮

    相关文章

      网友评论

          本文标题:SwiftUI Widget IntentConfigurati

          本文链接:https://www.haomeiwen.com/subject/fxfllltx.html