是否可以添加一个 UIView 作为 UINavigationBar 的背景

Is it possible to add a UIView as UINavigationBar's background

我正在尝试为 UINavigationBar 创建一个特定的背景,但我不想使用图像或纯色,我有一个我创建的自定义 UIView 并且在 drawRect 方法中,我正在绘制一些东西,我希望它成为 UINavigationBar 的背景。

可能吗?

这是我的自定义视图:

class GradientColorView : UIView {

    var colors : NSArray = NSArray() {
        didSet {
            setNeedsDisplay()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

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

    override func drawRect(rect: CGRect) {

        var topRect : CGRect = CGRectMake(0, 0, rect.size.width, rect.size.height / 2.0)
        var firstColor : UIColor = self.colors[0] as! UIColor
        firstColor.setFill()
        UIRectFill(topRect)

        var bottomRect : CGRect = CGRectMake(0, rect.size.height/2.0, rect.size.width, rect.size.height/2.0)
        var secondColor : UIColor = self.colors[1] as! UIColor
        secondColor.setFill()
        UIRectFill(bottomRect)
    }
}

当然还有 Swift:)

所以我找到了我的问题的答案,我所做的是创建一个名为 CustomNavigationBarUINavigationBar 子类并像这样覆盖 init 方法:

class CustomNavigationBar: UINavigationBar {

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = UIColor.someColor()
        let view : UIView = UIView(frame: CGRectMake(0, 20, frame.size.width, 44))
        self.addSubview(view)
    }

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

    override func drawRect(rect: CGRect) {

    }
}

然后我在包含 UINavigationBar:

UIViewController 上添加了这个方法
func styleCustomNavigationBar() {

    self.navigationController?.setNavigationBarHidden(true, animated: false)
    var navigationBar : CustomNavigationBar = CustomNavigationBar(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 64.0))
    var navigationItem : UINavigationItem = UINavigationItem()
    var backButton : UIBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "backButtonDidClicked")
    navigationItem.leftBarButtonItem = backButton
    navigationBar.items = [navigationItem]
    self.view.addSubview(navigationBar)
}

我使用 this and question and this 网站来找到解决方案。

尽情享受吧!