Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to give separation between TableView cells

I want to get lines of separation between every two table view cells, but not to create extra sections which I do not need.

For example:

enter image description here

like image 431
Fausto Checa Avatar asked Nov 06 '25 02:11

Fausto Checa


1 Answers

  1. Create a Custom TableViewCell.
  2. Contain your required views within a vertical StackView.
  3. Add a UIView at the bottom of the StackView and set a height constraint to the size of the whitespace you require (i.e 10px).
  4. Set a constraint for the height of the StackView to your required cell height (i.e. 70px)
  5. Create a reference to the StackView height Constraint

class CustomCell: UITableViewCell {

    @IBOutlet weak var cellLabel: UILabel!
    @IBOutlet weak var bottomSpace: UIView!
    @IBOutlet weak var stackViewHeight: NSLayoutConstraint!

}

enter image description here

In viewDidLoad:

tableView.estimatedRowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none

In your cellForRowAtIndexPath:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as? CustomCell else { return UITableViewCell() }

        if indexPath.row % 2 == 0 {
            cell.bottomSpace.isHidden = true
            cell.stackViewHeight.constant = 70.0 //Normal cell height
        } else {
            cell.bottomSpace.isHidden = false
            cell.stackViewHeight.constant = 80.0 //Cell height + whitespace
        }

        cell.cellLabel.text = data[indexPath.row]

        return cell
    }

enter image description here

like image 64
rbaldwin Avatar answered Nov 09 '25 01:11

rbaldwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!