LoginSignup
12
5

More than 3 years have passed since last update.

【Swift】カスタムセルで文字列やめませんか?

Last updated at Posted at 2021-03-30

はじめに

カスタムセルなどを利用するときに、tableView.register(UINib(nibName: "CustomCellNib", bundle: nil),
forCellReuseIdentifier: "CustomCellId")
こんな感じでtableViewにカスタムセルを登録していませんか?
これだと、プログラマが気付かぬうちに文字列の一文字を消してしまっても、Xcodeはエラーを出してくれません。ビルドして初めてエラーが出るのです。できれば文字列を打たずに済ませたいですよね。その方法をご紹介します。

実装

スクリーンショット 2021-03-30 10.07.53.png
Xibを作成して、以下のように付け足してください。

class MyTableViewCell: UITableViewCell {

    static var identifier: String { String(describing: self) }
    static var nib: UINib { UINib(nibName: String(describing: self), bundle: nil) }

}

そして、以下のようにControllerviewDidLoad()でセルを登録しましょう。ちなみに、カスタムセルのidをインスペクタで登録する必要はありません。

tableView.register(MyTableViewCell.nib, forCellReuseIdentifier: MyTableViewCell.identifier)

そして、UITableViewDataSourcecellForRowAtで以下のようにセルのidentifierを同じように打てば終わりです。

let cell = tableView.dequeueReusableCell(withIdentifier: MyTableViewCell.identifier, for: indexPath) as! MyTableViewCell
return cell

おわりに

文字列を極力打たないようにしたり、同じ文字列はハードコーディングしたりすることは、修正が入った時に修正箇所が一箇所で済んだり、今回紹介したような方法などではXcodeの補完が扱えるようになるので、タイプミスも減ります。メリットしかないので、ぜひ使ってみてください。(スニペットなどに登録しておくといいかもしれません。)

12
5
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
12
5