Swift 如何从Sqlite数据库加载表视图中的数据,UISwitch的状态取决于数据库中的保存状态
我想从数据库(SQlite)加载Swift 如何从Sqlite数据库加载表视图中的数据,UISwitch的状态取决于数据库中的保存状态,swift,swift4,Swift,Swift4,我想从数据库(SQlite)加载TableView中的数据,并根据DataBase中的保存状态(开/关)在set中加载UISwitch状态。这是我的密码 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Parenta
TableView
中的数据,并根据DataBase
中的保存状态(开/关)在set中加载UISwitch
状态。这是我的密码
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ParentalMovieTableViewCell", for: indexPath) as! ParentalMovieTableViewCell
let db = xxxDataBase()
lockArray = db.getLockInfo(catg: tabName)
if lockArray.isEmpty == true
{
cell.itemLbl.text = parentalMovieArray[indexPath.row]
cell.itemSwitch.isOn = true
cell.itemSwitch.tag = indexPath.row
cell.itemSwitch.addTarget(self, action: #selector(self.switchChanged(_sender:)), for: .valueChanged)
}
else
{
cell.itemLbl.text = parentalMovieArray[indexPath.row]
cell.itemSwitch.tag = indexPath.row
cell.itemSwitch.addTarget(self, action: #selector(self.switchChanged(_sender:)), for: .valueChanged)
for i in parentalMovieArray
{
for j in lockArray{
if i == j.item
{
cell.itemSwitch.isOn = true
}
else
{
cell.itemSwitch.isOn = false
}
}
}
}
@objc func switchChanged(_sender:UISwitch!)
{
// print("Table view switch changed\(_sender.tag)")
// print("The switch is\(_sender.isOn ? "ON" : "OFF")")
if _sender.isOn == false
{
print(_sender.tag)
var value = parentalMovieArray[_sender.tag]
print(value)
restrictMovieArray.append(value)
print(restrictMovieArray)
}
else if _sender.isOn == true
{
print(_sender.tag)
var value1 = parentalMovieArray[_sender.tag]
print(value1)
if let index = restrictMovieArray.index(of: value1) {
restrictMovieArray.remove(at: index)
print(restrictMovieArray)
}
}
}
1-)在tableView(\utableview:UITableView,cellForRowAt indexath:indexPath)中从数据库检索数据实际上非常昂贵,因为委托方法会被多次调用,特别是当用户滚动时,它会降低应用程序的性能,常见的解决方案是在viewdiload
中获取数据,将其存储在viewcontrollers成员中,并在需要时使用它
2-如果lockArray.isEmpty==true
和否则
块前3行相同,因此可以将其移动到这些块下面
您能澄清一下您的问题吗?ParentalMovierRay中的for i循环毫无意义cellForRowAt
每行调用一次。感谢您的更正。。请告诉我任何解决办法我的问题是。。。(我有一个tableView,其中每个单元格都包含一个标签和一个开关。当数据加载到tableView中时,所有开关都显示为打开状态。我希望当用户关闭任何开关并按下“完成”按钮时,开关状态可以保存在数据库中,当用户重新打开应用程序时,数据来自数据库,开关显示acco根据保存开关状态(开/关),不是全部开或关。我有一个表格视图,其中每个单元格都包含一个标签和一个开关。。在tableView中加载数据时,所有开关均显示打开状态。。我希望当用户关闭任何开关并按下“完成”按钮时,开关状态(打开或关闭)可以保存在数据库中,当用户重新打开应用程序时,数据来自数据库,开关根据保存开关状态(打开/关闭)显示,而不是全部打开或关闭。假设您有一个自定义UITableViewCell
包含开关,您必须侦听开关的更改事件,并通过委托方法(您应该实现)通知包含的viewcontroller。将单元格的开关值存储在数组中。然后,您还应该监听“完成”按钮的点击事件,以便在用户点击时更新数据库。