首页 > 解决方案 > 如何从Sqlite数据库加载表视图中的数据,UISwitch的状态是根据数据库中的保存状态

问题描述

我想TableView从 DataBase(SQlite) 加载数据,并UISwitch根据DataBase. 这是我的代码

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)
        }
    }
}

标签: swiftswift4

解决方案


1-)在委托方法中从数据库中检索数据tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)实际上是非常昂贵的,因为它会被调用很多次,尤其是当用户滚动时,它会降低您的应用程序性能,常见的解决方案是获取数据 viewDidLoad并将其存储在 viewcontrollers 成员中并使用它当你需要的时候。

2-)if lockArray.isEmpty == trueelse块的前 3 行相同,因此您可以将其移动到这些块下方。

你能澄清你的问题吗?


推荐阅读