那麼,如果你只想使用CALayers假設你的TableView是覆蓋設備的整個寬度你可以嘗試的TableCell的awakeFromNib此代碼。
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)
}
,你會得到的輸出爲: ![enter image description here](https://i.stack.imgur.com/MwHVJ.png)
也會使你的tableview分離器顏色以清除
self.tableView.separatorColor = UIColor.clearColor()
所以它不會得到你的層重疊。
我可以觀察到,現在每當插入新行時,單元格的邊界就不會消失。
或者
我們可以只使用一個UIImageView在小區故事板,並提供一個顏色有以下限制。
添加的UIImageView
![enter image description here](https://i.stack.imgur.com/s4vB5.png)
添加約束到的UIImageView
![enter image description here](https://i.stack.imgur.com/t1TKH.png)
就搞定!
還有一個備用溶液來實現這一點使用貝塞爾路徑
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)
}
試試看。
我認爲你可以通過額外的子圖層(CALayer具有背景顏色和高度)獲得相同的視覺效果,並且完全避免繪圖。但它當然不是你的問題的答案:) – sage444
@ sage444如果它是一個工作的替代品,請添加它作爲答案。 –
我們可以在故事板本身的單元格底部有一個2像素的簡單uiimageview,並在那裏提供一個顏色...這將作爲邊框。你還需要調用單元格setNeedsDisplay ..以便再次調用drawRect方法嗎? –