UILabel Background Color Leaks to Border

前端 未结 6 1939
予麋鹿
予麋鹿 2021-02-19 03:48

I\'m creating a UILabel to which I set the background color and corner radius with the following code:

self.scoreLabel.backgroundColor = [UIColor DISRed];// cust         


        
6条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 04:13

    For those who are still facing the issue of border color leaking out: Go through the below code, please note you will need to set frames & border width as per your requirement, I'm setting the position as view's center

     let badgeSize: CGFloat = 10
     let redBadge = UIView(frame: CGRect(x: view.center.x, y:view.center.y, width: badgeSize, height: badgeSize))
     redBadge.layer.borderColor = UIColor.white.cgColor
     redBadge.layer.borderWidth = 2
     redBadge.backgroundColor = .red
     redBadge.layer.cornerRadius = badgeSize * 0.5
     redBadge.clipsToBounds = true
     redBadge.layer.masksToBounds = true
     redBadge.maskLayerOnView(radius: badgeSize * 0.5)
     view.addSubview(redBadge)
    

    Secondly, we need to write an extension on UIView

    extension UIView{
     func maskLayerOnView(radius: CGFloat){
       let maskLayer = CAShapeLayer()
       maskLayer.path = UIBezierPath(roundedRect: self.bounds,
                        byRoundingCorners: [.allCorners], 
                        cornerRadii: CGSize(width: radius, 
                        height: radius)).cgPath
       self.layer.mask = maskLayer
     }
    }
    

    This code snippet removes the border color separating out, one can replicate this behaviour on any kind of views.

    For detailed explanation please see this article.

提交回复
热议问题