onAppear不允许保存/更新选择器值的更改?

如何解决onAppear不允许保存/更新选择器值的更改?

我正在构建一个Edit View,该视图允许用户对列表项进行更新并将其保存回核心数据和列表中。为此,我使用.onAppear操作在适当字段中从列表中传递值。

所有数据都会适当地传递,并且切换和文本字段使我可以轻松进行更改并将其保存回核心数据并更新列表项。但是,如果我尝试更改选择器值(emojiChoice)并选择一个新值,则选择器值不会更改或保存回Core Data。

当我注释掉选择器变量(emojiChoice)的onAppear操作时,选择器现在允许我选择所需的值并将其保存回Core Data。我还具有另一个视图,该视图允许用户创建与该“编辑视图”几乎相同的项目,但减去onAppear操作也可以正常工作。选择器允许用户选择表情符号。因为有很多表情符号,所以我创建了一个数组,而只是将所选表情符号的数组索引作为Int传递。

如何解决此问题,以允许选择器显示要编辑的值并允许对其进行更改?

这是“编辑视图”的代码:

struct editRemindr: View {
@Environment(\.managedObjectContext) var moc
@Environment(\.presentationMode) var presentationMode

let emojiList = EmojiList()
@ObservedObject var reminder: ReminderEntity
@State private var showingDeleteAlert = false

// Form Variables
@State var notifyOn = true
@State var emojiChoice = 0
@State var notification: String
@State var notes: String

// Delete Reminder Function
func deleteAction() {
    moc.delete(reminder)
    // try? self.moc.save()
    presentationMode.wrappedValue.dismiss()
}

// View Controller
var body: some View {
    Form {

        // On/Off Toggle
        Toggle(isOn: $notifyOn) {
            Text("On/Off")
        }

        // Emoji Picker
        Picker(selection: $emojiChoice,label: Text("Emoji")) {
            ForEach(0 ..< emojiList.emojis.count) {
                Text(self.emojiList.emojis[$0])
            }
        }

        // Notification Text
        Section(header: Text("NOTIFICATION")) {
            HStack {
                TextField("Write your notification...",text: $notification)
                    .onReceive(notification.publisher.collect()) {
                        self.notification = String($0.prefix(60)) // <---- SET CHARACTER LIMIT
                }
                Text("\(notification.count) / 60")
                    .font(.caption)
                    .foregroundColor(.gray)
            }
        }

        // Notes Text
        Section(header: Text("NOTES")) {
            VStack {
                MultiLineTextField(text: $notes).frame(numLines: 6)
                    .padding(.top,5)
                    .onReceive(notes.publisher.collect()) {
                        self.notes = String($0.prefix(240)) // <---- SET CHARACTER LIMIT
                }
                Text("\(notes.count) / 240")
                    .font(.caption)
                    .foregroundColor(.gray)
                    .frame(maxWidth: .infinity,alignment: .trailing)
            }
        }

        // Save Changes Button
        Section() {
            Button (action: {
                self.reminder.dateCreated = Date()
                self.reminder.notifyOn = self.notifyOn
                self.reminder.emojiChoice = Int64(self.emojiChoice)
                self.reminder.notification = self.notification
                self.reminder.notes = self.notes

                try? self.moc.save()

                self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("SAVE CHANGES")
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                    .font(.body)
            }        .padding()
                .frame(maxWidth: .infinity)
                .background(Color.green)
                .padding(.vertical,-6)
                .padding(.horizontal,-15)

            // Cancel Button
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("Cancel")
                    .frame(maxWidth: .infinity)
            }
        }
    }

    // Make List Items Appear in Fields
    .onAppear(perform: {
        self.notifyOn = self.reminder.notifyOn
        self.emojiChoice = Int(self.reminder.emojiChoice)
        self.notification = self.reminder.notification ?? "unknown"
        self.notes = self.reminder.notes ?? "unknown"
    }) 
        .alert(isPresented: $showingDeleteAlert) {
            Alert(title: Text("Delete Reminder"),message: Text("Are you sure you want to delete this Reminder?"),primaryButton: .destructive(Text("Delete")) {
                self.deleteAction()
                },secondaryButton: .cancel()
            )
    }
    .navigationBarTitle("Edit Reminder")
    .navigationBarItems(trailing: Button(action: {self.showingDeleteAlert = true
    }) {
        Image(systemName: "trash")

    })
} 

// Creates Text Limits
class TextLimit: ObservableObject {
    @Published var text = "" {
        didSet {
            if text.count > characterLimit && oldValue.count <= characterLimit {
                text = oldValue
            }
        }
    }
    let characterLimit: Int

    init(limit: Int = 5){
        characterLimit = limit
    }

}

如果有帮助,这是带有列表的内容视图的代码。

struct ContentView: View {

@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: ReminderEntity.entity(),sortDescriptors: [NSSortDescriptor(keyPath: \ReminderEntity.dateCreated,ascending: false)])
var reminder: FetchedResults<ReminderEntity>

@State private var showingAddScreen = false
@State var showWelcomeScreen = false

let emojiList = EmojiList()

//Toggle Control
@State var notifyOn = true

// Save Items Function
func saveItems() {
    do {
        try moc.save()
    } catch {
        print(error)
    }
}

// Delete Item Function
func deleteItem(indexSet: IndexSet) {
    let source = indexSet.first!
    let listItem = reminder[source]
    moc.delete(listItem)
}

// View Controller
var body: some View {
    VStack {
        NavigationView {
            ZStack (alignment: .top) {

                // List View
                List {
                    ForEach(reminder,id: \.self) { notification in
                        NavigationLink(destination: editRemindr(reminder: notification,notification: notification.notification ?? "unknown",notes: notification.notes ?? "unknown")) {
                            // Text within List View
                            HStack {
                                // MARK: TODO
                                // Toggle("NotifyOn",isOn: true)
                                // .labelsHidden() // Hides the label/title
                                Text("\(self.emojiList.emojis[Int(notification.emojiChoice)]) \(notification.notification!)")
                            } 
                        }
                    } 
                    .onDelete(perform: deleteItem)
                }

                    // Navigation Items
                    .navigationBarTitle("",displayMode: .inline)
                    .navigationBarItems(
                        leading:
                        HStack {

                            Button(action: {
                                self.showWelcomeScreen.toggle()
                            }) {
                                Image(systemName: "info.circle.fill")
                                    .font(.system(size: 24,weight: .regular))
                            }.foregroundColor(.gray)

                            // Positioning Remindr Logo on Navigation
                            Image("remindrLogoSmall")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                //.frame(width: 60,height: 60,alignment: .center)
                                .padding(.leading,83)
                                .padding(.top,-10)
                        },// Global Settings Navigation Item
                        trailing: NavigationLink(destination: globalSettings()){
                            Image("settings")
                                .font(Font.title.weight(.ultraLight))
                        }.foregroundColor(.gray)
                )

                // Add New Reminder Button
                VStack {
                    Spacer()
                    Button(action: { self.showingAddScreen.toggle()
                    }) {
                        Image("addButton")
                            .renderingMode(.original)
                    }
                    .sheet(isPresented: $showingAddScreen) {

                        newRemindr().environment(\.managedObjectContext,self.moc)

                    } 
                }
            }
        }  .sheet(isPresented: $showWelcomeScreen) {
            welcomeScreen()
        }
    }
}

Example

解决方法

尝试以下

    // Emoji Picker
    Picker(selection: $emojiChoice,label: Text("Emoji")) {
        ForEach(0 ..< emojiList.emojis.count,id: \.self) { // << added id !!
            Text(self.emojiList.emojis[$0])
        }
    }
,

我为选择器值创建了一个自定义绑定,它似乎可以解决问题。感谢Reddit user End3r117为我指出正确的方向!

// View Controller
var body: some View {
    
    let reminderChoice = Binding(
        get: { Int(self.reminder.emojiChoice) },set: { self.reminder.emojiChoice = Int64($0) }
    )
    return
        Form {
            
            // On/Off Toggle
            Toggle(isOn: $notifyOn) {
                Text("On/Off")
            }

            // Emoji Picker
            Picker(selection: reminderChoice,label: Text("Emoji")) {
                ForEach(0 ..< self.emojiList.emojis.count,id: \.self) {
                    Text(self.emojiList.emojis[$0])
                }
            }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-