在UITableViewCell上设置自定义分隔符插入

问题描述 投票:4回答:3

在我的UITableView中,我想要一个“居中”的分隔符效果,其中分隔符从左侧收缩30pt,从右侧收缩30°。我已经设法从Interface Builder设置TableView本身的'Custom Insets'属性,但我不能通过代码重现这种行为(我必须这样做)。

特别是,使用这段代码:

self.tableView.separatorColor = .green
self.tableView.separatorStyle = .singleLine
self.tableView.separatorInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)

还有这一个:

@objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView:  UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "recent_cell") as! TPExpandableTableViewCell
    //setting cell insets
    cell.separatorInset = separatorInset
    cell.item = items[indexPath.row]
    return cell
}

我在iPhone 6S模拟器上获得了以下输出:

Separator

似乎分隔符内容视图收缩,但分隔符背景视图不会收缩。我还尝试删除设置单元格separatorInset的行,结果是插入等于UIEdgeInset.zero

我可以确认绿色下面的白线是与分隔符相关的视图,因为如果我将separatorStyle更改为.none,它就会消失

有帮助吗?

ios swift uitableview separator uiedgeinsets
3个回答
2
投票

制作自定义分隔符的最佳方法是禁用UITableView分隔符,并在单元格内创建一个具有所需高度的视图,例如1px,然后将约束添加到视图中,使其位于单元格的中心底部。


12
投票

基本上,第一段代码对于设置分隔符插入,颜色和样式是正确的,即:

self.tableView.separatorColor = .green
self.tableView.separatorStyle = .singleLine
self.tableView.separatorInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)

单元格的separatorInset中的一个用于单元格的内容。所以我对你在这里想要达到的目标感到困惑。从你的上一个短语开始,你的内容缩小了,这是由'cell.separatorInset = separatorInset'引起的,你不知道怎么回事。

所以我建议你删除这行代码:

cell.separatorInset = separatorInset

2
投票

Problem:

分隔符后面的空白实际上属于单元格的backgroundColor,而不是单元格的contentView

Solution

因此,在创建自定义单元格设置时,contentView.backgroundColor不会更改该空白,但设置cell.backgroundColor将会。

例:

将其添加到自定义单元格的初始化程序中。

cell.backgroundColor = UIColor.red
© www.soinside.com 2019 - 2024. All rights reserved.