また1からこつこつと

最高はひとつじゃないと信じてまたがんばります。

【Swift3】UITableView separator のおはなし

UITableViewのcellとcellの間にある線がある。これをseparatorという。(そのまま)
こいつに関して幾つか知見を得たのでメモ。

画面の左端まで線を到達させる

separatorはデフォルトでは画面の左端まで到達せずに切れてる。
f:id:mjk0513:20170330233851p:plain:w300
これを左端までつける方法。

tableView.separatorInset = .zero

これでOK。
f:id:mjk0513:20170330233916p:plain:w300

色も変えることができる。

tableView.separatorColor = UIColor()

f:id:mjk0513:20170330234848p:plain:w300

ここまでカスタマイズできるのはすごい。

ただ、これだとindexPath == 0、つまり1番上のcellの上に線が入らない。
こういったことを実装したい場合は、cellにUIViewを追加するしかないっぽい。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let cell = UITableViewCell(style: .default, reuseIdentifier: "MyCell")
 cell.textLabel?.text = items[indexPath.row]
 if indexPath.row == 0{
  let separatorView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 1))
  separatorView.backgroundColor = UIColor.red
  cell.addSubview(separatorView)
 }
 return cell
}

f:id:mjk0513:20170330235420p:plain:w300

これextensionつくってgithubで公開してる。
github.com

ただ、didSelectRowされたときに、deselectRowを指定してると描画が変な感じになっちゃう。
どうすればいいか考えてみます。