问题
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