1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

チェックマークをRealmを使って保持する!!

Last updated at Posted at 2022-04-22

はじめに

ToDoアプリ等でよく使われる、
TavbleViewを使った、セルをタップするとチェックマークを付ける挙動を付けた所、tableView.reloadData()すると、チェックマークが外れた状態 (セルが選択されていない状態)になってしまいます。

これでは何をチェックしたのか解らないので、本末転倒な結果になります。
なので、tableView.reloadData()してもチェックマーク(セルが選択した状態)を付いた状態にする為に私が実践したやり方を紹介します。

ロジック(論理,筋道)を考える

1.チェックマークを保持する為の変数を定義する

 @objc dynamic var checkMark: Bool = false

私はセルが選択していない状態をfalse,選択している状態をtrueにする事にしました!!

2.変数checkMarkがセルが選択された状態になるとtrue,選択解除されるとfalseになる(保存される)状態を作る

セル選択時のメソッド

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        try! realm.write {
            list[indexPath.row].checkMark = true
        //listは表示したいセルの配列の名前ですね
        }       
    }

セル選択解除時のメソッド

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        
            try! realm.write {
                list[indexPath.row].checkMark = false
            }
        }

RealmStudioではこんな感じで動いてます
ezgif.com-gif-maker.gif

3.TableViewが表示される際に、選択状態だったセルを選択状態にする

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        
        cell.textLabel?.text = list[indexPath.row].title
        //チェックマークがtureの時に選択状態にする
        if list[indexPath.row].checkMark == true {
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        //それ以外は非選択状態にする    
        }else {
            tableView.deselectRow(at: indexPath, animated: false)
        }
        return cell
    }

これで起動時でもTableViewの更新時でもチェックマークを保持する事が出来ました!!
ezgif.com-gif-maker (2).gif

以上です!!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?