How to set top left and right corner radius with desired drop shadow in UITabbar?

后端 未结 5 670
萌比男神i
萌比男神i 2021-01-05 03:05

I\'ve spent almost a couple of hours to figure it out. However, it did not happen and finally, I had to come here. Two things are required to be achieved: <

5条回答
  •  时光说笑
    2021-01-05 03:40

    To add any radius or shape you can use a UIBezierPath. The example that I put has left and right corners with a radius and you can use more designable personalizations if you want.

    @IBDesignable class TabBarWithCorners: UITabBar {
        @IBInspectable var color: UIColor?
        @IBInspectable var radii: CGFLoat = 15.0
    
        private var shapeLayer: CALayer?
    
        override func draw(_ rect: CGRect) {
            addShape()
        }
    
        private func addShape() {
            let shapeLayer = CAShapeLayer()
        
            shapeLayer.path = createPath()
            shapeLayer.strokeColor = UIColor.gray.withAlphaComponent(0.1).cgColor
            shapeLayer.fillColor = color?.cgColor ?? UIColor.white.cgColor
            shapeLayer.lineWidth = 1
        
            if let oldShapeLayer = self.shapeLayer {
                layer.replaceSublayer(oldShapeLayer, with: shapeLayer)
            } else {
                layer.insertSublayer(shapeLayer, at: 0)
            }
        
            self.shapeLayer = shapeLayer
        }
    
        private func createPath() -> CGPath {
            let path = UIBezierPath(
                roundedRect: bounds,
                byRoundingCorners: [.topLeft, .topRight],
                cornerRadii: CGSize(width: radii, height: 0.0))
        
            return path.cgPath
        }
    }
    

提交回复
热议问题