LoginSignup
2

More than 3 years have passed since last update.

[Swift 5]セルの下線を消したいが、特定のセルの下にだけ画面幅いっぱいの罫線を表示したい時

Posted at

罫線を個別で表示する方法と、セクションのヘッダー表示で実現する方法の2通りがあると思います。

今回はリストを2つに分ける目的での罫線だったので、Sectionで実現し他場合の方法の備忘録です。

まず、デフォルトで表示されている罫線を非表示にします

Storyboardで設定する場合

Storyboard -> Tableview -> Separator

を、DefaultからNoneに変更する

コードで設定する場合

tableView.separatorStyle = .none

ヘッダーを生成して任意の箇所でのみ表示する

そして、色を指定する必要がないならHeaderの高さを1pxなどと指定するだけOKです!

しかし…今回は色の指定があったためHeader用のViewを作成するメソッドを使いました。

// ヘッダーを生成
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    // 今回は1つ目のセクションと2つ目のセクションの間に罫線を引きたかったので1(2番目の意)を指定
    let sectionWithHeader = 1
    // 罫線が欲しいセクション
    if section == sectionWithHeader {
        // UIViewを生成して色を指定
        let view = UIView(frame: .zero)
        view.backgroundColor = .black
        return view
    }
    return nil
}
// ヘッダーの高さを指定
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == sectionWithHeader {
        return 1.0
    }
    return 0
}

前述の通り、色等を指定しないのであれば、heightForHeaderInSectionの使用だけでOKです。

※TableViewのStyleがPlainのままの想定です。Groupedの場合はまた違った表示になってしまうかと思います。

後はセクションごとにセルの中身を実装すればOK

通常通り以下のDataSourceメソッドを実装しましょう。

// セクションの数
func numberOfSections(in tableView: UITableView) -> Int { }
// 行の数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { }
// セルの中身
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { }

参考: https://qiita.com/takashings/items/693ba4b31d07dbe90778

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
2