Customize separator per cell in UITableView

Your problem is that cell.bounds.size is not correct when this code is executed, so you can use self.view.bound.size.width using UIViewController.view bounds or directly .greatestFiniteMagnitude I prefer use this last one

Modified Code should be something like this

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = countryCodeView.dequeueReusableCell(withIdentifier: "CountryCell") as! CountryCell
        let country = countries[indexPath.row]

        cell.flag.text = country.flag
        cell.countryCode.text = "+\(country.countryCode)"
        cell.countryName.text = country.name
        
        if indexPath.row == 0 {
            cell.countryCode.font = UIFont(name: "ProximaNovaA-Bold", size: 16)
            cell.countryName.font = UIFont(name: "ProximaNovaA-Bold", size: 16)
            cell.separatorInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
            cell.tickIcon.isHidden = false
        } else {
            cell.countryCode.font = UIFont(name: "ProximaNovaA-Regular", size: 16)
            cell.countryName.font = UIFont(name: "ProximaNovaA-Regular", size: 16)
            cell.separatorInset = UIEdgeInsets(top: 0, left: .greatestFiniteMagnitude, bottom: 0, right: 0)
            cell.tickIcon.isHidden = true
        }
        
        return cell
    }

As alternative you can have an extension for all TableViewCells

extension UITableViewCell {
    func hideSeparator() {
        self.separatorInset = UIEdgeInsets(top: 0, left: .greatestFiniteMagnitude, bottom: 0, right: 0)
        if #available(iOS 11.0, *) {
            self.directionalLayoutMargins = .zero
        }
    }
}

This can be used simply calling this method on cells that you need separator hidden

cell.hideSeparator()

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top