我正在使用嵌入 UITableViewCell 中的 UISWitch 更新一些核心数据条目。
当切换开关时,我需要它来刷新表格,尽管此时 UISwitch 只是停留在原处。
我怀疑这与我使用的型号有关?下面是来自 UITableVIewCell 的代码,我在其中更新了核心数据条目,然后使用 TableView 引用,尝试重新加载表上的数据。不过,除非我退出 View 并返回,否则 UI 不会重新加载,因此我知道核心数据实体正在正确更新。
我怀疑这是因为我的 SurveyQuestionReference 始终设置为相同的值?
class SurveyQuestionTableViewCell: UITableViewCell {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
@IBOutlet weak var lblQuestion: UILabel!
@IBOutlet weak var toggQuestion: UISwitch!
var surveyQuestionReference : SurveyQuestion?
var tableViewReference : UITableView?
@IBAction func toggledQuestion(sender: AnyObject) {
let tempContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
tempContext.parentContext = self.managedObjectContext
tempContext.performBlock({
let entityName = "CoreDataObject"
let request = NSFetchRequest(entityName: entityName)
request.predicate = NSPredicate(format: "workId = %@", self.surveyQuestionReference!.workId)
do {
let results = try tempContext.executeFetchRequest(request) as? [NSManagedObject]
if results!.count > 0{
if let moc = self.managedObjectContext{
moc.performBlockAndWait({
[unowned self] in
for result in results!{
result.setValue(self.toggQuestion.on, forKey: (self.surveyQuestionReference?.property)!)
}
})
}
}
do {
try tempContext.save()
} catch let error {
print(error)
}
}catch{
print("error")
}
})
print(sender)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// load data
dispatch_async(dispatch_get_main_queue()) {
// update ui
self.tableViewReference!.reloadData()
}
}
}
最佳答案
我通过在重新加载表格之前设置 models 属性解决了这个问题:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// load data
dispatch_async(dispatch_get_main_queue()) {
// update ui
self.surveyQuestionReference?.answer = self.toggQuestion.on
self.tableViewReference!.reloadData()
}
}
关于ios - UISwitch 粘在 UITableViewCell 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34946297/