func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
if (tableView == self.orderDetailsTableView)
{
//Top Left Right Corners
let maskPathTop = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.TopLeft, .TopRight], cornerRadii: CGSize(width: 5.0, height: 5.0))
let shapeLayerTop = CAShapeLayer()
shapeLayerTop.frame = cell.bounds
shapeLayerTop.path = maskPathTop.CGPath
//Bottom Left Right Corners
let maskPathBottom = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.BottomLeft, .BottomRight], cornerRadii: CGSize(width: 5.0, height: 5.0))
let shapeLayerBottom = CAShapeLayer()
shapeLayerBottom.frame = cell.bounds
shapeLayerBottom.path = maskPathBottom.CGPath
//All Corners
let maskPathAll = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.TopLeft, .TopRight, .BottomRight, .BottomLeft], cornerRadii: CGSize(width: 5.0, height: 5.0))
let shapeLayerAll = CAShapeLayer()
shapeLayerAll.frame = cell.bounds
shapeLayerAll.path = maskPathAll.CGPath
if (indexPath.row == 0 && indexPath.row == tableView.numberOfRowsInSection(indexPath.section)-1)
{
cell.layer.mask = shapeLayerAll
}
else if (indexPath.row == 0)
{
cell.layer.mask = shapeLayerTop
}
else if (indexPath.row == tableView.numberOfRowsInSection(indexPath.section)-1)
{
cell.layer.mask = shapeLayerBottom
}
}
}
我们实际上正在做的是,如果部分只有一行,则在所有边上进行操作;如果部分有多行,则在第一行顶部和最后一行底部进行操作...属性BottomLeft、BottomRight、topLeft、TopRight应该是rect corner类型(在输入时来自xcode的建议...还有一个具有相同名称的content corner属性..因此请检查)
看起来你的tableView包含一个UIView
,所以只需在cellForRowAtIndexPath
中添加这些行。如果没有,请添加一个UIView并将半径添加到该UIView,然后将该视图添加到单元格中(cell.addSubView(YOURVIEW)
)。
cell.contentView.layer.cornerRadius = 10
cell.contentView.layer.masksToBounds = true
如果您想自定义边框,可以
cell.layer.borderColor = UIColor.grayColor().CGColor
cell.layer.borderWidth = 5
更新
如果想在viewForHeaderInSection
中添加此功能,
需要创建一个视图 let view = UIView() 并向您的视图添加半径。
view.layer.cornerRadius = 10
view.layer.masksToBounds = true
我设置了contentView.layer.cornerRadius = 10
,但仍然没有显示;这是由于cell.contentView.backgroundColor
默认为nil
,导致背景色透明,因此它的cell.backgroundColor
作为其背景颜色。
将单元格的背景颜色设置为.clear
,在我的情况下会显示tableView的背景颜色(非白色),然后会按预期显示圆角,如下所示:
// Cell's init()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
backgroundColor = .clear // this will show parent views bkgColor
//(in my case non-white)
// where the sharp corner is
contentView.layer.cornerRadius = 10.0 // set corner radius
contentView.backgroundColor = .white // set tableViewCells background color to what you want
/* do stuff */
}
尝试:
override func draw(_ rect: CGRect) {
super.draw(rect)
self.layer.cornerRadius = 8
self.clipsToBounds = true
}
在您的 TableViewCell 中
或者:
cell.layer.cornerRadius = 8
cell.clipsToBounds = true
self.layer.cornerRadius = 4.0
self.clipToBounds = true
或者您可以将一个视图放置在单元格内作为背景视图,并设置其圆角半径和clipToBounds属性。
self.backgroundView.layer.cornerRadius = 4.0
self.backgroundView.clipToBounds = true