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

don*_*dev 4 uitableview separator ios uiedgeinsets swift

在我的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)
Run Code Online (Sandbox Code Playgroud)

还有这一个:

@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
}
Run Code Online (Sandbox Code Playgroud)

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

分隔器

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

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

有帮助吗?

nfe*_*s76 12

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

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

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

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

cell.separatorInset = separatorInset
Run Code Online (Sandbox Code Playgroud)


Ali*_*ari 2

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