LoginSignup
1
2

More than 3 years have passed since last update.

xib で定義されてる cell の使いやすくようにする

Posted at

問題点

ベタ書きでエラーが発生する可能性は十分あるんで悩ましい。

let nib = UINib(nibName: "MyCell", bundle: nil)

tableView.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "MyCellIdentifier")

やりたいこと

  • Embedded Framework 対応
    • bundle に入れるべき値は cell class によって変わる
  • nibNameの入れ方をスマートに

解決方法

String(describing:)

let nibName = String(describing: MyCell.self)

動的に Bundle を取得

let bundle = Bundle(for: MyCell.self)

Bundle が動的に取得できれば Cell が他の target/framework に定義されても困らない。

合併してみる

合併したらこんな感じになります

let nibName = String(describing: MyCell.self)
let bundle = Bundle(for: MyCell.self)

let nib = UINib(nibName: nibName, bundle: bundle)

よしなにヘルパーを設ける

extension UITableViewCell {
    public static var nib: UINib {
        return UINib(nibName: nibName, bundle: Bundle(for: self))
    }

    static var nibName: String {
        return String(describing: MyCell.self)
    }
}

使い方

tableView.register(MyCell.nib, forCellReuseIdentifier: "MyCellIdentifier")

この書き方にするなら、ヒューマンエラ可能性も低くになると思います。
次は cell reuse identifier の方を書こうと思います。

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