swift-runtime实现导航栏封装无需继承动态提供属性控制导航栏样式

在iOS应用开发中,导航栏(NavigationBar)是用户界面中的重要组成部分,用于展示当前页面的标题和提供返回等操作。为了使应用具有统一且可定制的导航栏样式,开发者经常需要进行封装。本文将深入探讨如何利用Swift的runtime机制来实现一个导航栏封装,无需子类化,而是通过动态提供属性来控制导航栏样式。了解Swift的runtime。Swift runtime是Swift程序在运行时使用的库,它提供了访问和修改对象属性、方法、类型信息的能力。在不修改原有代码的情况下,我们可以通过runtime对对象进行操作,比如在导航栏封装中,我们可以动态地设置导航栏的颜色、字体、透明度等属性。实现这个功能的关键在于`UINavigationController`的代理方法和KVC(Key-Value Coding)。我们可以创建一个工具类,例如`YINNavigationService`,并实现`UINavigationControllerDelegate`协议。在这个类中,我们可以定义一系列静态方法,用于设置和获取导航栏的各种样式属性,如`navigationBarTitleColor`、`navigationBarBackgroundColor`等。 ```swift class YINNavigationService { static var navigationBarTitleColor: UIColor? { get { return getKeyPathValue(forKey: #keyPath(UINavigationBar.titleTextAttributes))?[NSAttributedString.Key.foregroundColor] as? UIColor } set { setKeyPathValue(newValue, forKey: #keyPath(UINavigationBar.titleTextAttributes), withKey: NSAttributedString.Key.foregroundColor) } } //其他类似的方法... } ```这里的`getKeyPathValue`和`setKeyPathValue`是利用KVC来获取和设置导航栏属性的方法,它们通过反射找到对应属性并进行操作。接下来,我们需要在每个需要自定义导航栏样式的ViewController中,设置其所属的`UINavigationController`的代理为`YINNavigationService`。同时,在页面的生命周期方法中,比如`viewDidLoad`和`deakeFromNib`,我们根据需求调用工具类中的方法来设置导航栏的样式。 ```swift override func viewDidLoad() { super.viewDidLoad() navigationController?.delegate = YINNavigationService.self YINNavigationService.navigationBarTitleColor = .red //设置导航栏标题颜色} override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) YINNavigationService.navigationBarTitleColor = nil //还原导航栏标题颜色} ```这样,我们就实现了在不侵入具体页面逻辑的情况下,动态控制导航栏样式的功能。这种封装方式的好处在于代码复用性和可维护性都得到了提升,同时也避免了因为忘记恢复导航栏样式而导致的界面问题。在提供的`YINNavgationDemo-master`压缩包中,应该包含了这个功能的完整示例代码。通过查看和学习这个示例,你可以更好地理解如何运用Swift runtime和KVC来实现导航栏的动态封装。在实际项目中,可以根据需要进一步扩展这个工具类,添加更多自定义的导航栏样式属性,以满足各种复杂的界面需求。
folder
swift-runtime实现导航栏封装无需继承动态提供属性控制导航栏样式 预估大小:110个文件
file
.gitignore 1KB
file
MASConstraintMaker.h 6KB
file
MASUtilities.h 6KB
file
MASConstraint.h 8KB
file
NSLayoutConstraint+MASDebugAdditions.h 326B
file
NSArray+MASShorthandAdditions.h 1016B
file
Masonry.h 802B
file
MASViewConstraint.h 1KB
file
NSArray+MASAdditions.h 3KB
file
MASConstraint+Private.h 2KB
file
View+MASShorthandAdditions.h 5KB
file
MASViewAttribute.h 1KB
file
View+MASAdditions.h 5KB
file
ViewController+MASAdditions.h 891B
file
MASCompositeConstraint.h 494B
file
MASLayoutConstraint.h 505B
file
Aspects.h 4KB
file
UIViewController+YINNav.h 1KB
file
YINMethodHook.h 913B
file
AppDelegate.h 280B
zip 文件大小:113.49KB