在Swift中对UINavigationBar进行子类化

我正在尝试创建一个自定义UINavigationBar类,然后使用Storyboard将其设置为我的UINavigationController的NavigationBar的类。

这是我的UINavigationBar类的代码:

 class CustomNavBar: UINavigationBar { override func drawRect(rect: CGRect) { super.drawRect(rect) // Drawing code self.backgroundColor = UIColor.orangeColor() let myLabel = UILabel(frame: CGRect(x: 0, y: 4, width: 600, height: 36)) myLabel.backgroundColor = UIColor.purpleColor() myLabel.textColor = UIColor.yellowColor() myLabel.text = "Custom NavBar!" self.addSubview(myLabel) } } 

然后,在Interface Builder中,我使用Identity Inspector将其设置为我的UINavigationControllerNavigationBar的类。

当我运行应用程序 – 它冻结。 它挂起在LaunchScreen.xib ,并没有做任何事情。

为什么这样做? 这样做的正确方法是什么?

在Swift上:

File-New-File- iOS Source – Cocoa Touch类 – 选择子类:UINavigationBar并将其命名为CustomNavigationBar。

 class CustomNavigationBar: UINavigationBar { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.redColor() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func drawRect(rect: CGRect) { } }