iOS 指定UIView的某几个圆角或边框(Swift)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kmonarch/article/details/82892300

在开发中我们经常会遇到对一个UIView 设置四个圆角的情况,这种情况是很好处理的。但是如果遇到只设置其中的某几个圆角的情况怎么办呢?有一种方法是通过UIBezierPath的方法来做,代码如下:

/**

* 设置uiview 的任意圆角

**/

func SetMutiBorderRoundingCorners(_ view:UIView,corner:CGFloat)

{

    let maskPath = UIBezierPath.init(roundedRect: view.bounds,

    byRoundingCorners: [UIRectCorner.bottomLeft, UIRectCorner.topRight],

    cornerRadii: CGSize(width: corner, height: corner))

    let maskLayer = CAShapeLayer()

    maskLayer.frame = view.bounds

    maskLayer.path = maskPath.cgPath

    view.layer.mask = maskLayer

}

此外,我们还会遇到给一个UIview设置某几条边框而不是全部边框的情况,解决办法如下:

func SetBorderWithView(_ view:UIView,top:Bool,left:Bool,bottom:Bool,right:Bool,width:CGFloat,color:UIColor)

{
    
    if top

    {

        let layer = CALayer()

        layer.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: width)

        layer.backgroundColor = color.cgColor

        view.layer.addSublayer(layer)

    }

    if left

    {

        let layer = CALayer()

        layer.frame = CGRect(x: 0, y: 0, width: width, height: view.frame.size.height)

        layer.backgroundColor = color.cgColor

        view.layer.addSublayer(layer)

    }

    if bottom

    {

        let layer = CALayer()

        layer.frame = CGRect(x: 0, y: view.frame.size.height - width, width: width, height: width)

        layer.backgroundColor = color.cgColor

        view.layer.addSublayer(layer)

    }

    if right

    {

        let layer = CALayer()

        layer.frame = CGRect(x: view.frame.size.width - width, y: 0, width: width, height: view.frame.size.height)

        layer.backgroundColor = color.cgColor

        view.layer.addSublayer(layer)

    }

}

以上两种方法效果如下图所示

Simulator Screen Shot - iPhone 8 Plus - 2018-08-10 at 13.51.22.png

猜你喜欢

转载自blog.csdn.net/kmonarch/article/details/82892300