在 Swift 中继承 UINavigationBar [英] Subclassing UINavigationBar in Swift
问题描述
我正在尝试创建一个自定义 UINavigationBar
类,然后使用 Storyboard
将其设置为我的 UINavigationController
的类导航栏.
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.
这是我的 UINavigationBar
类的代码:
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)
}
}
然后,在 Interface Builder 中,我使用 Identity Inspector
将其设置为我的 UINavigationController
的 NavigationBar
的类.
Then, in Interface Builder, I use the Identity Inspector
to set this as the class of the NavigationBar
of my UINavigationController
.
当我运行应用程序时 - 它冻结了.它挂在 LaunchScreen.xib
上,什么也不做.
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?
推荐答案
关于 Swift:
File-New-File-iOS Source-Cocoa Touch 类-选择 UINavigationBar 的子类并将其命名为 CustomNavigationBar.
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) {
}
}
这篇关于在 Swift 中继承 UINavigationBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!