如何使导航栏彩色且半透明 (iOS)?

How do you make a navigation bar colored and translucent (iOS)?

如何使导航栏既半透明又具有色调,如下图所示:

我还希望它保留半透明导航栏的默认模糊效果(所以我不希望它看起来和图片一模一样,因为我也想要模糊效果。) 我觉得这应该很容易,但我花了一个小时寻找解决方案,但没有任何效果符合我的要求。 另外,我更喜欢 Interface Builder 解决方案,但如果没有,swift 也可以。

只需设置导航栏的颜色,然后设置透明度即可。

navigationController?.navigationBar.barTintColor = UIColor.green
navigationController?.navigationBar.alpha = 0.5

应该这样做。

只需 select "Navigation Bar" 界面生成器中的 UINavigationController(不是其他 ViewController 的 NavigationItem)并更改 "barTintColor"

变色部分来了from here. I just added the blur part from here。我不知道这是否是模糊的最佳解决方案,但它确实有效。您将需要对导航栏进行子类化,但这并不痛苦。发现如果模糊视图稍微降低了 alpha 效果会更好,你将不得不尝试一下。

extension UIColor {
    func toImage() -> UIImage? {
        return toImageWithSize(size: CGSize(width: 1, height: 1))
    }
    func toImageWithSize(size: CGSize) -> UIImage? {
        UIGraphicsBeginImageContext(size)

        if let ctx = UIGraphicsGetCurrentContext() {
            let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            ctx.setFillColor(self.cgColor)
            ctx.addRect(rectangle)
            ctx.drawPath(using: .fill)
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return colorImage
        } else {
            return nil
        }
    }
}

extension UIImage {
    func imageWithAlpha(alpha: CGFloat) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: CGPoint.zero, blendMode: .normal, alpha: alpha)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

class CustomNavBar: UINavigationBar {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setBackgroundImage(UIColor.blue.toImage()?.imageWithAlpha(alpha: 0.5), for: .default)
        addBlurEffect()
    }

    func addBlurEffect() {
        let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
        var frame = bounds
        frame.origin.y -= 20
        frame.size.height += 20
        visualEffectView.frame = frame
        visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        visualEffectView.alpha = 0.9
        insertSubview(visualEffectView, at: 0)
        sendSubview(toBack: visualEffectView)
    }
}