Ios 可调整大小视图的圆角

Ios 可调整大小视图的圆角,ios,swift,uiview,uibezierpath,cashapelayer,Ios,Swift,Uiview,Uibezierpath,Cashapelayer,我一直在使用下面显示的代码来圆角视图的选定角,但是我现在很难在一个可调整大小的视图作为图层上实现这一点?不会在每次调整视图大小时更新 extension UIView { func roundCorners(corners:UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CG

我一直在使用下面显示的代码来圆角视图的选定角,但是我现在很难在一个可调整大小的视图作为图层上实现这一点?不会在每次调整视图大小时更新

extension UIView {
    func roundCorners(corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

titleLabelView.roundCorners(corners: [.topLeft, .topRight], radius: 10)
有一个类似的问题,但它非常古老,都是在objC中完成的

对于可调整大小的视图,是否有办法在swift中舍入选定的角点

-----编辑-----

所以本质上我有一个文本表,我已经根据文本的大小调整了它的大小

在大多数情况下,我只能使用:

myTextLabel.layer.cornerRadius = 10
但是,这会完成所有4个角。因此,如果我只想将前2个四舍五入,那么我需要使用上面的扩展名。现在,因为我正在使用ScrollViewDiEndDecelling设置标签的内容(我需要获取collectionView中心单元格的indexPath,以便设置文本标签)

在这种情况下,使用viewDidLayoutSubViews不起作用,因为加速结束和布局之间存在延迟。我尝试在viewDidLayoutSubViews中使用相同的代码(不检查中心索引),但结果是相同的

当我不使用任何圆角时,标签的大小会正确调整


我也遇到过类似的问题,我使用如下函数解决了这个问题

DispatchQueue.main.async(execute: {
    self.roundCorners(.allCorners, radius: 6, borderColor: nil, borderWidth: nil)
})
我经常在
UITableViewCell
中使用此函数,我的整个代码如下所示

private var didLayoutSubview = false {
    didSet {
        DispatchQueue.main.async(execute: {
            self.roundCorners(.allCorners, radius: 6, borderColor: nil, borderWidth: nil)
        })
    }
}

override func layoutSubviews() {
    if !self.didLayoutSubview {
        self.didLayoutSubview = true
    }
    super.layoutSubviews()
}
所以基本上,在主线程中调用这个函数是有帮助的,我在
layoutSubivews
中调用它,因为我认为它就是这个地方

我的职能

func roundCorners(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor?, borderWidth: CGFloat?) {
    let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))

    let mask = CAShapeLayer()
    mask.frame = self.bounds
    mask.path = path.cgPath
    self.layer.mask = mask

    if borderWidth != nil {
        addBorder(mask, borderWidth: borderWidth!, borderColor: borderColor!)
    }
}

在不检查相关问题(我希望得到答案)的情况下,您能解释确切的问题吗?从Obj-C到Swift的转换非常简单。你试过什么?您的问题相当模糊。特别是,在您引用的问题中,请特别注意在
viewdilayoutsubviews
中调整大小。您是否将uiView子类化以实现这一点,或者是否为其提供uiView?
func roundCorners(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor?, borderWidth: CGFloat?) {
    let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))

    let mask = CAShapeLayer()
    mask.frame = self.bounds
    mask.path = path.cgPath
    self.layer.mask = mask

    if borderWidth != nil {
        addBorder(mask, borderWidth: borderWidth!, borderColor: borderColor!)
    }
}