Swift Tableview сохранить значение UISlider с помощью Realm - PullRequest
0 голосов
/ 01 октября 2019

Я столкнулся с парой проблем, с которыми мне было интересно, если кто-то может помочь. Любой совет будет высоко ценится!

Я использую Realm для сохранения объектов (списки Todo в категории). Каждый список Todo имеет tableView, а каждая пользовательская ячейка имеет UISlider. Пользователь может изменить значение ползунка в таблице, и я надеюсь (1) сохранить значение ползунка с помощью Realm и (2) сохранить значение в ячейке, когда пользователь прокручивает вверх / вниз табличное представление и между viewControllers.

Буду признателен за любую помощь, которую вы можете оказать !!!

Вот мой соответствующий код:

Модели:

class Cagtegory : Object {
    @objc dynamic var name : String = ""
    @objc dynamic var colour : String = ""
    @objc dynamic var dateCreated : Date?
    let todoList = List<ToDo>()
}
class ToDo: Object {
    @objc dynamic var label : String = ""
    @objc dynamic var value : Int = 0
    var category = LinkingObjects(fromType: Category.self, property: "todoList")
}

Я также определил customCell с помощьюползунок ...

class ToDoCell: UITableViewCell {
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var valueSlider: UISlider!
    var sliderValue : Int = 0

    //PROBLEM HERE: the following method was set-up to make sure reused cells don't take up values from previous cells. However, when I scroll the table up/down, it resets my slider selection! 
    override func prepareForReuse() {
        super.prepareForReuse()
            valueSlider.value = valueSlider.minimumValue
    }

    @IBAction func sliderChanged(_ sender: UISlider) {
            sliderValue = Int(valueSlider.value)
    }
}

Тогда в моем ViewController у меня есть вид таблицы ...

class ToDoList UIViewController, UITableViewDelegate, UITableViewDataSource {
        let realm = try! Realm()
        var selectedCategory : Category?
    var todoItems = Results<ToDo>
        var todoSliderValues : [Int] = []

        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(UINib(nibName: "ToDoCell", bundle: nil), forCellReuseIdentifier: "CustomToDoCell") 
        }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomToDoCell", for: indexPath) as! ToDoCell
        if let item = todoItems?[indexPath.row] {
              cell.label.text = item.label
        }

        //PROBLEM HERE (I think). I don’t know how to make sure that as soon as the slider value is changed, it is saved in my realm database
        interconnectionStrength[indexPath.row] = cell.sliderValue
        writeToRealm(sliderValue = interconnectionStrength[indexPath.row])
        return cell
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.reloadData()
            tableView.deselectRow(at: indexPath, animated: true)
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return todoItems?.count ?? 1
        }

        func writeToRealm(sliderValue: Int) {
            if let currentCategory = selectedCategory {
                do {
                    try realm.write {
                    currentSimulation.todoList.append(sliderValue) //doesn’t capture the latest value of the slider unfortunately
                }
                } catch {
                    print(error)
                }
            }
        }

}
...