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

SwiftUI如何基于用户选中的Core Data Tag更新视图展示自定义子视图

解决方案核心逻辑:通过页面回调完成选中Tag的反向传值,再基于响应式状态控制视图渲染


步骤1:给TagListView添加选中回调

给TagListView新增闭包属性,用于将用户选中的Tag回传给上游页面:

struct TagListView: View {
    // 新增选中Tag的回调属性
    var onSelectTag: (Tag) -> Void
    
    // 原有其他属性保持不变
    @FetchRequest(entity: Tag.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Tag.title, ascending: true)]) var tagList : FetchedResults<Tag>
    @Environment(\.presentationMode) var presentationMode
    @StateObject var viewModel = TagListViewModel()
    
    // ... 其余代码保持不变
}

修改Tag点击事件,触发回调传值:

Button {
    // 替换原有TODO,执行回调传入选中Tag
    onSelectTag(tag)
    // Dismiss页面逻辑保持不变
    self.presentationMode.wrappedValue.dismiss()
} label: {
    TagView(title: tag.title ?? "Tag", color: tagColour, darkText: false)
}

步骤2:修改AddTaskView的标签区域逻辑

替换标签区域的原有TODO代码,完成回调接收、状态更新、条件渲染三个逻辑:

//MARK: Task.tag Field
HStack {
    Text("Tag")
    
    Spacer()
    
    NavigationLink(
        destination: TagListView(onSelectTag: { selectedTag in
            // 将选中的Tag赋值给ViewModel的响应式属性
            viewModel.tag = selectedTag
        }),
        label: {
            // 条件渲染:有选中Tag就显示Tag视图,无则显示添加按钮
            if let selectedTag = viewModel.tag {
                let tagColour = Color(red: selectedTag.colourR, green: selectedTag.colourG, blue: selectedTag.colourB, opacity: selectedTag.colourA)
                TagView(title: selectedTag.title ?? "Tag", color: tagColour, darkText: false)
            } else {
                AddTagButtonView()
            }
        }
    )
    .accentColor(.black)
}

步骤3:补全任务保存逻辑(可选但必要)

修改AddTaskViewModel的addTask方法,把选中的Tag关联到新建的Task上(需提前在Core Data的Task实体中添加指向Tag的一对一关联属性):

func addTask(taskTitle: String, taskInfo: String, taskDueDate: Date) {
    let newTask = Task(context: coreDataHandler.container.viewContext)
    
    newTask.title = taskTitle
    newTask.info = taskInfo
    newTask.dateCreated = Date()
    newTask.dateDue = taskDueDate
    newTask.completed = false
    newTask.archived = false
    // 新增Tag关联逻辑
    newTask.tag = tag
    
    coreDataHandler.save()
}

内容的提问来源于stack exchange,提问作者nix.codes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:36:02