Как установить закругленные углы и тени для UITabBar? - PullRequest
2 голосов
/ 15 мая 2019

Я хочу установить радиус угла и тень для UITabBar, но у меня проблема. Это мой код

tabBar.barTintColor = .white
tabBar.isTranslucent = false

tabBar.layer.shadowOffset = CGSize(width: 0, height: 5)
tabBar.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
tabBar.layer.shadowOpacity = 1;
tabBar.layer.shadowRadius = 25;

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

Если я изменю tabBar.layer.masksToBounds = false на = true -> будет отображаться угловой радиус, но тени не будет.

1 Ответ

0 голосов
/ 12 июля 2019

Я нашел способ сделать это, добавив отдельный теневой слой для панели вкладок:

    tabBar.clipsToBounds = true
    tabBar.layer.cornerRadius = Siz_TabBar_CornerRadius

    shadowLayer = CALayer()
    shadowLayer.frame = tabBar.frame
    shadowLayer.backgroundColor = UIColor.clear.cgColor
    shadowLayer.cornerRadius = yourTabBarCornerRadius
    shadowLayer.shadowColor = yourShadowColor.cgColor
    shadowLayer.shadowRadius = yourShadowRadius
    shadowLayer.shadowOpacity = 1.0
    shadowLayer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]

    // This is important so the shadow doesn't lag content
    // which is scrolling underneath it.  You should tell the tab
    // bar layer to rasterize as well, the rounded corners can cause
    // performance issues with animated content underneath them.
    shadowLayer.shouldRasterize = true
    shadowLayer.rasterizationScale = UIScreen.main.scale

    // The shadow path is needed because a shadow won't
    // display for a layer with a clear backgroundColor
    let shadowPath = UIBezierPath(roundedRect: shadowLayer.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: yourTabBarCornerRadius, height: yourTabBarCornerRadius))

    // The mask makes it so that the shadow doesn't draw on
    // top of the tab bar, filling in the whole layer
    let maskLayer = CAShapeLayer()
    let maskPath = CGMutablePath()

    // This path goes around the outside of the possible shadow radius, so that the
    // shadow is between this path and the tap bar
    maskPath.addRect(CGRect(x: -yourShadowRadius, y: -yourShadowRadius, width: shadowLayer.frame.width + yourShadowRadius, height: shadowLayer.frame.height + yourShadowRadius))

    // The shadow path (shape of the tab bar) is drawn on the inside
    maskPath.addPath(shadowPath.cgPath)
    maskLayer.path = maskPath

    // This makes it so that the only shadow layer content that will
    // be drawn is located in between the two above paths
    maskLayer.fillRule = .evenOdd
    shadowLayer.mask = maskLayer

    // View here is the tab bar controller's view
    view.layer.addSublayer(shadowLayer)
...