在 Swift 中子类化 UINavigationBar

sir*_*333 5 subclass uinavigationbar uinavigationcontroller ios swift

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

这是我的班级的代码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)
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,在 Interface Builder 中,我使用 将Identity Inspector其设置为NavigationBar我的UINavigationController.

当我运行该应用程序时 - 它冻结了。它挂起LaunchScreen.xib并且不执行任何操作。

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

A.G*_*A.G 4

在斯威夫特上:

文件 - 新建 - 文件 - iOS 源 - 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) {

        }   
    }
Run Code Online (Sandbox Code Playgroud)