我有一个自定义UITableViewCell,我使用drawRect绘制一个简单的底部边框: override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(r
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)
}
这非常有效.但是,当我插入带动画的行时,所有单元格的边框消失,并在插入动画完成时再次出现:
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: cells.count - 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade)
知道怎么避免这个吗?
那么你可以在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)
}
你会得到输出:
还要使您的tableview分隔符颜色清除
self.tableView.separatorColor = UIColor.clearColor()
这样它就不会与你的图层重叠.
我可以观察到,无论何时插入新行,现在没有细胞边界消失.
另外
我们可以在单元格故事板中使用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)
}
这也产生相同的输出.
编辑:
如果我们没有为单元格使用故事板或笔尖并以编程方式创建单元格,那么我们可以执行以下解决方法:
在CustomTableViewCell类中创建一个属性
var borderLayer:CALayer!
现在在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)
}
试试吧.
