LoginSignup
0
1

More than 3 years have passed since last update.

TableViewのCell入れ替えでViewが透過されてしまったあなたへ

Last updated at Posted at 2019-06-07

まくら

iOSアプリといえばUITableViewでございます。たぶん。
今回はそんなUITableViewの小ネタをひとつ。

UITableViewは割と簡単な設定でセルの入れ替えを実現させてくれます。

extension TableWorkViewController: UITableViewDataSource {
    // ...省略...

    // 移動可能
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    // 移動実行
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        print("source: \(sourceIndexPath)")
        print("dest: \(destinationIndexPath)")
    }
}

こんな感じで設定してやって、どこかで

self.tableView.isEditing = true

してやると、
SS06071401.png

こんな感じで入れ替えアイコンが表示されるようになります。
基本的なものでいいのならこれだけ。簡単。

では実際に入れ替えてみましょう。

SS002.png

お気づきだろうか?

セルの上にUIViewを乗せているのですが、見えなくなっていますね。
どうやら入れ替えの時はセルの上に乗っているUIViewは透明にされてしまっているようです。

何やらちょっと気持ち悪いので、対策を考えてみましょう。

ほんだい

という訳で本題。

自分も地味にハマってしまったのですが、ナイスな力技で解決している方がいたので、マネさせて頂きました。

参考:
https://medium.com/@vhart/tableview-cell-reordering-keep-the-color-4c03623d2399

最高!この力技感!

元ネタの方を見て頂けばわかる通り、移動の時にUIViewbackgroundColorに透明がセットされてしまうので、強制的に色を保持してやろうという訳です。

そんなわけで作ったものがこちら

/// セルの入れ替え時に色をのキープしておくためのView
class TableWorkColorKeepView: UIView {

    /// キープ用のbackgroundColor
    @IBInspectable var keepBackgroundColor: UIColor = .clear {
        didSet {
            self.backgroundColor = self.keepBackgroundColor
        }
    }

    /// 背景色
    override var backgroundColor: UIColor? {
        set {
            // キープしている色と異なればリターン
            guard newValue == keepBackgroundColor else {
                return
            }
            super.backgroundColor = newValue
        }
        get {
            return super.backgroundColor
        }
    }
}

これを使うと、

Simulator Screen Shot - iPhone Xʀ - 2019-06-07 at 18.19.24.png

こうなります。

キープ用の色を用意して、背景色が変更される時にその色と異なったら無視してやっているだけですね。
背景色をセットしたい場合はkeepBackgroundColorの方に設定してやる感じです。
(Storyboardで初期値設定したかったので@IBInspectableしてやっています)

しまいに

力技なので用法用量にご注意を。
もっとスマートなやり方あれば教えてつかあさい。

0
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
0
1