首页 > 解决方案 > 根据需要在每个自定义 UITableViewCell 上设置分隔符插图

问题描述

我只能在表格视图级别上更改分隔符插图。如果我在 UITableViewCell 上创建自定义插图或尝试将其删除,则它不起作用。我有一个表格视图,在某些单元格中,我需要一个自定义分隔符插图,即左侧很少缩进并触及右侧的边距,而对于某些单元格,我根本不需要分隔符。

如果我设置bookWorkspaceTableView.separatorStyle = .none in viewDidLoad(),即使在我试图显示它的单元格上,我也根本看不到分隔符。如果我没有设置 `bookWorkspaceTableView.separatorStyle = .none',那么即使对于我不想看到的单元格,我也会看到分隔符。

下面的代码是我没有将表格视图上的分隔符样式设置为无的地方,我想隐藏默认的表格视图分隔符,但即使使用下面的代码我仍然看到它......我该如何修复它?:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        log.debug("MyPlaces::cellForRowAt \(indexPath.row)")

        if (indexPath.row == 0) {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "allDaySwitchCell") as? LeftLabelRightSwitch {
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.leftLabel.text = IndoorsLocalizedString.all_day.getLocalizedString()
                cell.leftLabel.textAlignment = .left

                cell.layoutMargins = UIEdgeInsets.zero
                cell.separatorInset = UIEdgeInsets.zero

                // Remove seperator inset
//                if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
//                    cell.separatorInset = .zero
//                }
//                // Prevent the cell from inheriting the Table View's margin settings
//                if cell.responds(to: #selector(setter: UITableViewCell.preservesSuperviewLayoutMargins)) {
//                    cell.preservesSuperviewLayoutMargins = false
//                }
//                // Explictly set your cell's layout margins
//                if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins)) {
//                    cell.layoutMargins = .zero
//                }

                //cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
                return cell
            }
        }

在此处输入图像描述

在此处输入图像描述

标签: iosswiftuitableview

解决方案


这对我来说也是一种痛苦。所以我不想使用 UITableView 中的默认分隔符。然后我创建自己的分隔符。为 UITableViewCell 创建一个扩展并设置我自己的。

extension UITableViewCell {
    func addSeperator() {
        let seperator = UIView(frame: CGRect(x: 0, y: contentView.frame.height - 1, width: contentView.frame.width, height: 1))
        seperator.backgroundColor = .seperator
        contentView.addSubview(seperator)
    }
}

在您的情况下,我认为您只需要此功能的选项来设置边距。


推荐阅读