我有以下代码从 CloudKit 获取数据,检查属性“Completed”是否为 false,如果是,则向 taskCount 添加 1。
迭代完任务后,它会更新按钮的内容和颜色。
问题是,代码全部执行后, View 需要几秒钟的时间才能真正更新,按钮上的数字以及颜色也会发生变化。
有没有办法在更新按钮颜色和内容后强制刷新或执行其他操作?
let taskManager = CloudKitTaskManager(database: CKContainer.defaultContainer().privateCloudDatabase)
taskManager.getSummaryOfTasks {
tasks in
for index in 0...tasks.count-1 {
if ("False" == tasks[index].completed){
self.taskCount = self.taskCount + 1
}
}
self.dueButton.setTitle(String(self.taskCount) + "\nOutstanding", forState: UIControlState.Normal)
if (self.taskCount == 0) {
self.dueButton.backgroundColor = UIColor(red:52/255, green:152/255, blue:219/255, alpha:1.0)
self.dueButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}else if(self.taskCount > 0 && self.taskCount <= 5){
self.dueButton.backgroundColor = UIColor(red:243/255, green:156/255, blue:18/255, alpha:1.0)
self.dueButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}else if(self.taskCount > 5){
self.dueButton.backgroundColor = UIColor(red:231/255, green:76/255, blue:60/255, alpha:1.0)
self.dueButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}
}
感谢您提前提供的任何帮助。
最佳答案
不保证 CloudKit 方法的完成处理程序在主队列上运行,因此您必须像这样将用户界面相关代码分派(dispatch)给它:
let taskManager = CloudKitTaskManager(database: CKContainer.defaultContainer().privateCloudDatabase)
taskManager.getSummaryOfTasks {
tasks in
for index in 0...tasks.count-1 {
if ("False" == tasks[index].completed){
self.taskCount = self.taskCount + 1
}
}
dispatch_async(dispatch_get_main_queue()) {
self.dueButton.setTitle(String(self.taskCount) + "\nOutstanding", forState: UIControlState.Normal)
if (self.taskCount == 0) {
self.dueButton.backgroundColor = UIColor(red:52/255, green:152/255, blue:219/255, alpha:1.0)
self.dueButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}else if(self.taskCount > 0 && self.taskCount <= 5){
self.dueButton.backgroundColor = UIColor(red:243/255, green:156/255, blue:18/255, alpha:1.0)
self.dueButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}else if(self.taskCount > 5){
self.dueButton.backgroundColor = UIColor(red:231/255, green:76/255, blue:60/255, alpha:1.0)
self.dueButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}
}
}
关于ios - 强制刷新 UI 以更快地更改按钮颜色和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32533566/