我有一个显示来自SQLite数据库的数据的单元格的collectionview。我也有一个从SQLite数据库中删除行的按钮。我想刷新collectonview并删除不再包含已删除行的单元格,但下面的代码段不起作用,行将从SQLite数据库中删除,但视图不会刷新,除非我离开该视图并返回到它。重新加载视图?
@IBAction func buttonViewHeartAction(sender: UIButton) {
print("buttonViewHeartAction tapped")
let face = self.faces[sender.tag]
if let imageURL = NSURL(string:face.image) {
let path = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true
).first!
let db = try! Connection("\(path)/db.sqlite3")
let table = Table("coffee_table")
let id = Expression<Int64>("id")
let name = Expression<String>("name")
let url = Expression<String>("url")
let alice = table.filter(url == face.directLink)
try! db.run(alice.delete())
dispatch_async(dispatch_get_main_queue(),{
self.collectionview.reloadData()
})
}
}
编辑2:
@IBAction func buttonViewHeartAction(sender: UIButton) {
print("buttonViewHeartAction tapped")
let face = self.faces[sender.tag]
if let imageURL = NSURL(string:face.image) {
let path = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true
).first!
let db = try! Connection("\(path)/db.sqlite3")
let table = Table("coffee_table")
let id = Expression<Int64>("id")
let name = Expression<String>("name")
let url = Expression<String>("url")
let alice = table.filter(url == face.directLink)
try! db.run(alice.delete())
var newfaces = [face]
self.faces = newfaces
dispatch_async(dispatch_get_main_queue(),{
self.collectionview.reloadData()
})
}
}
编辑3:
let path = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true
).first!
let db = try! Connection("\(path)/db.sqlite3")
let table = Table("coffee_table")
let id = Expression<Int64>("id")
let name = Expression<String>("name")
let url = Expression<String>("url")
var newfaces=[face]()
for tables in try! db.prepare(table) {
//getting the data at each index
let coffeefaceName = (tables[name]) as! String
let coffeefaceDirectLink = (tables[url]) as! String
let coffeefaceImage = (tables[url]) as! String
let newface = face(name:coffeefaceName,
directLink: coffeefaceDirectLink,
image:coffeefaceImage)
newfaces.append(newface)
}
dispatch_async(dispatch_get_main_queue(),{
self.faces = newfaces
self.collectionview.reloadData()
})
您确定在删除后已正确更新了collectionview数据数组吗? –
我这么认为。我的意思是,如果我离开视图并回到收集视图,删除的数据将不再显示。 – user3591436