Swift 中 UIView 的圆角 [英] Round Top Corners of a UIView in Swift

查看:59
本文介绍了Swift 中 UIView 的圆角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的代码圆顶角

I am trying to round top corners using below code

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

使用 myView.roundCorners(corners:[.topLeft, .topRight], radius: radius)

但它使视图的一侧四舍五入:

But it's rounding one side of the view:

这是在 tableView sectionHeader 如果我向下滚动然后向上滚动它使用相同的代码:

this is in a tableView sectionHeader if I scroll down then up it rounded using same code:

并且顶部折扣视图的角也使用相同的函数进行圆角.

感谢您的帮助.

更新如果我固定视图上的宽度,那么它就可以正常工作.

Update if I fix the width on the view then it works fine.

推荐答案

在@Paolo 的帮助下解决了这个问题,下面是工作代码.

Solved this with the help of @Paolo and below is the working code.

Swift 3.2

extension UIView {

    func roundCorners(corners:UIRectCorner, radius: CGFloat) {

        DispatchQueue.main.async {
            let path = UIBezierPath(roundedRect: self.bounds,
                                    byRoundingCorners: corners,
                                    cornerRadii: CGSize(width: radius, height: radius))
            let maskLayer = CAShapeLayer()
            maskLayer.frame = self.bounds
            maskLayer.path = path.cgPath
            self.layer.mask = maskLayer
        }
    }
}

要调用此函数,请使用下面的行并提及要圆的角

for calling this function use below line and mention which corners you want to round

self.myView.roundCorners(corners: [.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 8.0)

这篇关于Swift 中 UIView 的圆角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆