首页 > 解决方案 > 如何在 UITabBar 顶部创建圆角

问题描述

我想将角半径设置为 UITabBar 并设置阴影。它应该看起来像img1,但看起来像img2

我的代码:

  tabBar.barTintColor = .white
  tabBar.isTranslucent = false

tabBar.dropShadow(shadowColor: UIColor.lightGray, fillColor: UIColor.white, opacity: 1, offset: CGSize(width: 0, height: 5), radius: 25)

        tabBar.layer.masksToBounds = false
        tabBar.isTranslucent = true
        tabBar.barStyle = .blackOpaque
        tabBar.layer.cornerRadius = 13
        tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

和扩展

extension UIView{
    func dropShadow(shadowColor: UIColor = UIColor.black,
                    fillColor: UIColor = UIColor.white,
                    opacity: Float = 0.2,
                    offset: CGSize = CGSize(width: 0.0, height: 5.0),
                    radius: CGFloat = 10) -> CAShapeLayer {

        let shadowLayer = CAShapeLayer()

        shadowLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: radius).cgPath
        shadowLayer.fillColor = fillColor.cgColor
        shadowLayer.shadowColor = shadowColor.cgColor
        shadowLayer.shadowPath = shadowLayer.path
        shadowLayer.shadowOffset = offset
        shadowLayer.shadowOpacity = opacity
        shadowLayer.shadowRadius = radius
        layer.insertSublayer(shadowLayer, at: 0)
        return shadowLayer
    }
}

标签: swiftxcodeuitabbarcontrolleruitabbar

解决方案


  1. 添加扩展:
        extension UIView {
             func makeCornerTabBar(shadowColor: UIColor = UIColor.black,
                             fillColor: UIColor = UIColor.white,
                             opacity: Float = 0.2,
                             corners: UIRectCorner,
                             offset: CGSize = CGSize(width: 0.0, height: 5.0),
                             radius: CGFloat = 0.0) -> CAShapeLayer {
            
              let shadowLayer = CAShapeLayer()
              shadowLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
              shadowLayer.fillColor = fillColor.cgColor
              shadowLayer.shadowColor = shadowColor.cgColor
              shadowLayer.shadowPath = shadowLayer.path
              shadowLayer.shadowOffset = offset
              shadowLayer.shadowOpacity = opacity
              layer.mask = shadowLayer
              layer.insertSublayer(shadowLayer, at: 0)
              return shadowLayer
           }
      }
  1. 调用分机:

    tabBar.makeCornerTabBar(shadowColor: UIColor.lightGray, fillColor: UIColor.white, opacity: 1, corners: [.topLeft, .topRight], offset: CGSize(width: 0, height: 5), radius: 25)
    

推荐阅读