圆角半径仅适用于视图的左上角和左下角

Corner radius only for top and bottom left corner of a view

我只需要对视图的左上角和左下角进行圆角处理,所以我尝试了这个:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "teamCell", for: indexPath) as! TeamCell

    let view = cell.backgroundCellView
    let rectShape = CAShapeLayer()
    rectShape.bounds = (view?.frame)!
    rectShape.position = (view?.center)!
    rectShape.path = UIBezierPath(roundedRect: (view?.bounds)!, byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath
    view?.layer.mask = rectShape
    view?.layer.masksToBounds = true

    return cell
}

它工作得很好,但是在我设置约束(尾随、前导、顶部和底部 - 我需要一个响应式视图)后,只有左上角是圆形的,而另一个不是。我该如何解决?

尝试使用

view?.layer.cornerRadius = 15 

而不是

rectShape.path = UIBezierPath(roundedRect: (view?.bounds)!, byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath

试试这个

 let path = UIBezierPath(roundedRect:viewToRound.bounds, byRoundingCorners:[.TopLeftt, .BottomLeft], cornerRadii: CGSizeMake(20, 20))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.CGPath
    view.layer.mask = maskLayer

一个简单的方法是设置单元格内容视图的角半径,然后为了防止内容的右侧角变圆,您可以将它们限制为 x 尾随 space到内容视图(其中 x 是您的角半径)。不过,这确实需要您调整布局以考虑单元格右侧的额外填充。

从 iOS 11 和 Swift 4 开始,您可以使用 maskedCorners:

let myView = UIView()

myView.layer.cornerRadius = 15
myView.clipsToBounds = true

// Top Left Corner: .layerMinXMinYCorner
// Top Right Corner: .layerMaxXMinYCorner
// Bottom Left Corner: .layerMinXMaxYCorner
// Bottom Right Corner: .layerMaxXMaxYCorner
myView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]