Subclassing UINavigationBar in Swift

谁都会走 提交于 2019-12-22 08:42:12

问题


I'm trying to create a custom UINavigationBar class and then use the Storyboard to set it as the class of my UINavigationController's NavigationBar.

Here's the code of my UINavigationBar class:

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)
    }

}

Then, in Interface Builder, I use the Identity Inspector to set this as the class of the NavigationBar of my UINavigationController.

When I run the App - it freezes. It hangs up on the LaunchScreen.xib and doesn't do anything.

Why is doing that? What's the right way to go about doing this?


回答1:


On Swift:

File-New-File- iOS Source - Cocoa Touch class- Select Subclass of : UINavigationBar and Name it - 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) {

        }   
    }


来源:https://stackoverflow.com/questions/31116733/subclassing-uinavigationbar-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!