【问题标题】:Is it possible to add a UIView as UINavigationBar's background是否可以将 UIView 添加为 UINavigationBar 的背景
【发布时间】:2015-09-09 20:02:24
【问题描述】:

我正在尝试为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 :)

【问题讨论】:

    标签: ios swift uiview uinavigationbar


    【解决方案1】:

    所以我找到了我的问题的答案,我所做的是创建了一个名为 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) {
    
        }
    }
    

    然后我在拥有UINavigationBarUIViewController 上添加了这个方法:

    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 和问题以及this 网站来解决问题。

    享受吧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多