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

Ios 角半径仅适用于视图的左上角和左下角,ios,swift,uiview,constraints,cornerradius,Ios,Swift,Uiview,Constraints,Cornerradius,我只需要在视图的左上角和左下角转弯,所以我尝试了以下方法: func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "teamCell", for: indexPath) as! TeamCell let view = ce

我只需要在视图的左上角和左下角转弯,所以我尝试了以下方法:

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个尾随空间(其中x是角半径)。这确实需要调整布局,以考虑单元格右侧的额外填充

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

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]

上面的代码在哪里?在cellForRow中,调用dequeueReusableCell方法(我将编辑我的问题)后,您应该尝试在调用
super.layoutSubviews()后,将其移动到
UITableViewCell
子类的
layoutSubviews
方法
将构建掩码的代码放入单元格的子视图是正确的答案@贝奥武夫,你应该把它作为一个答案贴出来,这样OP就可以接受它了。它可能会在四个角落重复