ios - Swift 为透明导航栏创建子类

标签 ios swift uinavigationcontroller uinavigationbar

我在以下代码的帮助下在多个 View Controller 中完成了透明导航栏。我想减少主类文件中的代码行,也尽量避免代码重复。所以,我需要为下面的代码创建子类。请帮助我

    // NavigationBar Tranparant
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = .clear

最佳答案

如果您通过 Storyboard创建元素,那么只需创建 UINavigationBar 的子类并将您的属性添加到 awakeFromNib 函数中。

现在在您的 Storyboard中,选择 navigationController 的 navigationBar 并为其指定您刚刚创建的类(来自身份检查器)。

UINavigationBar 子类的示例:

import UIKit
class AppBaseNavigationBar : UINavigationBar{
    override func awakeFromNib() {
        super.awakeFromNib()

        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()

        self.titleTextAttributes = [
            NSAttributedStringKey.foregroundColor : UIColor.black
        ]
        self.isTranslucent = true 
    }
}

但是,如果您想通过代码使用它,即(let nav = UINavigationController(navigationBarClass: AppBaseNavigationBar.self, toolbarClass : nil))

您需要添加 override init(frame: CGRect)required init?(coder: NSCoder (后者是必需的)因为我们不是来自 Nib 并且awakeFromNib 将不会被调用。

所以你的子类如下:

import UIKit
class AppBaseNavigationBar : UINavigationBar{


    override init(frame: CGRect) {//for using custom view in code
        super.init(frame: frame)
        setupNavBar()
    }

    required init?(coder aDecoder: NSCoder) {// for using CustomView in IB
        super.init(coder: aDecoder)
        setupNavBar()
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        setupNavBar()

    }

    func setupNavBar(){
        // To avoid duplicate code, move your properties to a function.
        self.setBackgroundImage(UIImage(), for: .default)
        self.shadowImage = UIImage()

        self.titleTextAttributes = [
            NSAttributedStringKey.foregroundColor : UIColor.black
        ]
        self.isTranslucent = true
    }
}

override init(frame: CGRect) 在您以编程方式创建 View 时使用。 (这就是我们实现的原因,因为我们将以编程方式创建 NavigationController)

required init?(coder: NSCoder) 在从 storyboard/xib 创建 View 时使用。

因为后者是必需的,我们也在这里设置了我们的导航..

关于ios - Swift 为透明导航栏创建子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52025653/

相关文章:

ios - 如何在 UINavigationBar sizeToFit 中设置 UITextField?

ios - AVPlayer 在 302 重定向后无法为同一域发送 cookie

iphone - 来自 AVPlayer 对象的 AudioQueueLevelMeterState

ios - 如何测量给定字体类型和字体大小中最大字符的最大大小?

Swift - 在表格 View 中读取上面的单元格值

uinavigationcontroller - 更改半透明黑色 UINavigationBar 的颜色

iphone - 按创建日期对 NSURL 对象数组进行排序

ios - Swift Playground 错误 : extra argument 'timeout' in call

ios - 如何从地理点检索位置-(Parse.com 和 Swift)并使用 Xcode 6.2 在 map 上显示它

swift - 使 navigationBar 边框不可见