You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中实现基于指定数组的App Intents文本修改功能

基于SwiftUI+AppIntents实现Siri修改界面文本功能

作为编程新手,我需开发一款基于SwiftUI的应用,通过AppIntents实现以下功能:利用指定字符串数组["Mountain", "Car", "Ball"]中的元素,响应Siri指令修改界面Text组件。例如,当发出“嘿Siri,将文本设置为Ball”或“嘿Siri,将文本设置为Mountain”的指令时,界面文本需同步更改为对应内容。我已编写了基础的AppIntent代码,恳请协助完善实现逻辑。

基础代码:

struct chooseWord: AppIntent {
    @Parameter(title: "Word")
    var word: String
    
    static var title: LocalizedStringResource = "Change the text"
    static var description = IntentDescription("Changes the text on screen")
    
    static var openAppWhenRun: Bool = true
    static var parameterSummary: some ParameterSummary {
        Summary("Changes the word to ...")
    }
    @MainActor
    func perform() async throws -> some IntentResult {

        return .result(dialog: "Done!")
    }
}

实现步骤

1. 创建共享状态管理器

需要一个跨界面和Intent的共享状态,用来存储当前显示的文本,确保主线程更新:

import SwiftUI
import AppIntents

// 共享状态管理器
@MainActor
class TextViewModel: ObservableObject {
    static let shared = TextViewModel()
    @Published var currentWord: String = "初始文本"
}

2. 完善AppIntent的参数验证与状态更新

修改Intent代码,限制可选词范围并更新共享状态:

struct ChooseWordIntent: AppIntent {
    // 指定可选参数范围,Siri会自动识别这些选项
    @Parameter(title: "Word", options: ["Mountain", "Car", "Ball"])
    var word: String
    
    static var title: LocalizedStringResource = "修改界面文本"
    static var description = IntentDescription("将界面上的文本更改为指定内容")
    
    static var openAppWhenRun: Bool = true
    static var parameterSummary: some ParameterSummary {
        Summary("将文本更改为\(\.$word)")
    }
    
    @MainActor
    func perform() async throws -> some IntentResult {
        // 更新共享状态,同步到界面
        TextViewModel.shared.currentWord = word
        return .result(dialog: "已将文本设置为\(word)")
    }
}

3. 主界面绑定共享状态

在主视图中绑定共享状态,实时显示更新后的文本:

struct ContentView: View {
    @StateObject private var viewModel = TextViewModel.shared
    
    var body: some View {
        VStack(spacing: 20) {
            Text(viewModel.currentWord)
                .font(.largeTitle)
                .fontWeight(.bold)
            
            // 可选:手动测试按钮,方便调试
            Button("设置为Mountain") {
                viewModel.currentWord = "Mountain"
            }
            Button("设置为Car") {
                viewModel.currentWord = "Car"
            }
            Button("设置为Ball") {
                viewModel.currentWord = "Ball"
            }
        }
        .padding()
    }
}

4. 注册Intent

在App结构体中注册Intent,让系统识别:

@main
struct SiriTextChangeApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .intents(of: ChooseWordIntent.self)
    }
}

测试说明

  1. 运行应用,进入iPhone/iPad的「设置」→「Siri与搜索」→「所有快捷指令」,找到应用的「修改界面文本」指令并添加到Siri
  2. 说出“嘿Siri,修改界面文本为Ball”,应用会自动打开并同步更新界面文本

内容的提问来源于stack exchange,提问作者SirEdwardIII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:03:32