【问题标题】:Setting separator insets on each custom UITableViewCell as needed根据需要在每个自定义 UITableViewCell 上设置分隔符插图
【发布时间】:2025-11-24 02:00:01
【问题描述】:

我只能在表格视图级别上更改分隔符插入。如果我在 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
            }
        }

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    这对我来说也很痛苦。所以我不想使用 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)
        }
    }
    

    在你的情况下,我认为你只需要这个函数的选项来设置边距。

    【讨论】:

      最近更新 更多