UITableViewCell drawRect底部边框在insertRow上消失

Upv*_*ote 3 uitableview ios swift swift2

我有一个自定义UITableViewCell,我使用drawRect绘制一个简单的底部边框:

override func drawRect(rect: CGRect) {   
   let context = UIGraphicsGetCurrentContext()
   CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(rect))
   CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect))
   CGContextSetStrokeColorWithColor(context, UIColor(netHex: 0xEFEEF4).CGColor)
   CGContextSetLineWidth(context, 2)
   CGContextStrokePath(context)
}
Run Code Online (Sandbox Code Playgroud)

这非常有效.但是,当我插入带动画的行时,所有单元格的边框消失,并在插入动画完成时再次出现:

tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: cells.count - 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade)
Run Code Online (Sandbox Code Playgroud)

知道怎么避免这个吗?

Raj*_*ari 6

那么你可以在tablecell的awakeFromNib中尝试这个代码,如果你只想使用CALayers,假设你的TableView覆盖了设备的整个宽度.

override func awakeFromNib() {
    super.awakeFromNib()
    let borderLayer = CALayer()
    let lineHeight:CGFloat = 2
    borderLayer.frame = CGRect(x: 0, y: self.frame.height - lineHeight , width: UIScreen.mainScreen().bounds.width, height: lineHeight)
    borderLayer.backgroundColor = UIColor.redColor().CGColor
    self.layer.addSublayer(borderLayer)
}
Run Code Online (Sandbox Code Playgroud)

你会得到输出: 在此输入图像描述

还要使您的tableview分隔符颜色清除

self.tableView.separatorColor = UIColor.clearColor()
Run Code Online (Sandbox Code Playgroud)

这样它就不会与你的图层重叠.
我可以观察到,无论何时插入新行,现在没有细胞边界消失.

或者,
我们可以在单元格故事板中使用UIImageView,并提供具有以下约束的颜色.
添加UIImageView
在此输入图像描述

向UIImageView添加约束

在此输入图像描述

我们完成了!


使用Bezier Paths 还有一种替代解决方案可以实现这一目标

 override func awakeFromNib() {
    super.awakeFromNib()
    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.moveToPoint(CGPointMake(0, self.frame.height))
    linePath.addLineToPoint(CGPointMake(UIScreen.mainScreen().bounds.width, self.frame.height))
    line.lineWidth = 3.0
    line.path = linePath.CGPath
    line.strokeColor = UIColor.redColor().CGColor
    self.layer.addSublayer(line)
 }
Run Code Online (Sandbox Code Playgroud)

这也产生相同的输出.

编辑:

如果我们没有使用故事板或笔尖为单元格和编程创建单元格,那么我们可以这样做一个解决方法:

在CustomTableViewCell类中创建一个属性

var borderLayer:CALayer!
Run Code Online (Sandbox Code Playgroud)

现在在CustomTableViewCell类中有一个名为layoutSubviews的方法

override func layoutSubviews() {
    if(borderLayer != nil) {
        borderLayer.removeFromSuperlayer()
    }
    borderLayer = CALayer()
    let lineHeight:CGFloat = 2
    borderLayer.frame = CGRect(x: 0, y: self.frame.height - lineHeight , width: UIScreen.mainScreen().bounds.width, height: lineHeight)
    borderLayer.backgroundColor = UIColor.redColor().CGColor
    self.layer.addSublayer(borderLayer)
}
Run Code Online (Sandbox Code Playgroud)

试试吧.