可调整大小视图的圆角

时间:2017-02-14 04:41:58

标签: ios swift uiview uibezierpath cashapelayer

我一直在使用下面显示的代码来围绕视图的选定角落,但是现在我无法在可调整大小的视图中实现这一点作为图层?每次调整视图大小时都不会更新。

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)

有一个类似的问题here,但它很老,都是在objC中完成的。

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

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

基本上我所拥有的是一个文本表,我根据文本的大小设置了调整大小。

在大多数情况下,我可以使用:

myTextLabel.layer.cornerRadius = 10

然而,这有四个角落。因此,如果我想要排在前2位,那么我需要使用上面的扩展名。现在因为我使用scrollViewDidEndDecelerating来设置标签的内容(我需要获取collectionView中心的单元格的indexPath,所以我可以设置文本标签)

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    GeneralFunctions.getIndexOfCell(sender: self) { (index) in
        self.titleLabel.text = self.partArray[index].title
        self.titleLabel.roundCorners(corners: [.topLeft, .topRight], radius: 10)
        self.descriptionLabel.text = self.partArray[index].description
        self.descriptionLabel.roundCorners(corners: [.bottomLeft, .bottomRight], radius: 10)
        self.backgroundLabelView.layer.cornerRadius = 16
        self.backgroundLabelView.layoutIfNeeded()
        self.backgroundLabelView.layoutSubviews()
    }

}

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

enter image description here

当我不使用任何角落舍入时,标签会正确调整大小。

enter image description here

1 个答案:

答案 0 :(得分:1)

我有类似的问题,我已经通过使用像

这样的函数解决了它
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!)
    }
}
相关问题