ios - 是调用方法来改变导航栏的外观吗? swift 3

标签 ios swift3 uinavigationbar

我在 UINavigationController 中嵌入了几个 View Controller 。我想为每个 viewController 自定义导航栏标题的外观。调用setCustomTitleInNavBar 的最佳方法是什么? .如果在 viewDidLoad 中调用,self 还没有初始化,应用会崩溃。在 ViewWillAppear 中,当 View 显示给用户时,标题尚未显示。如果这不是正确的方法,请建议替代实现。

class CustomMethods {
  func setCustomTitleInNavBar(textValue:String, VC:UIViewController) -> UIView {
     let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
     titleLabel.text = textValue
     titleLabel.adjustsFontSizeToFitWidth = true
     titleLabel.textAlignment = NSTextAlignment.center
       VC.navigationItem.titleView = titleLabel
           return VC.navigationItem.titleView!
  }
}


//call method on the current view controller to modify the nav bar title
   class someViewController: UIViewController {
     override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(true)  
         setCustomTitleInNavBar(textValue: "Where to come?", VC: self)
  }
}

最佳答案

这是一种通过协议(protocol)实现它的方法:

// Protocol
protocol NavigationBarSetUpProtocol: class {

    // Add more param if needed
    func setupNavigationBar(with title: String)
}

// Default implemention
extension NavigationBarSetUpProtocol where Self: UIViewController {

    // Default implementation
    func setupNavigationBar(with title: String) {

        // configure you VC navigation item with : self.navigationItem.titleView = ...
    }

}

// VC A
class ViewControllerA: UIViewController, NavigationBarSetUpProtocol {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar(with: "HOME")
    }

}

// VC B
class ViewControllerB: UIViewController, NavigationBarSetUpProtocol {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar(with: "PROFILE")
    }

}

关于ios - 是调用方法来改变导航栏的外观吗? swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44096221/

相关文章:

c++ - Cocos2dx 如何在没有 Schedule Selector 的情况下每 5 秒调用一个函数?

ios - 无法隐藏状态栏—Swift 3,

swift3 - 如何更改 FSCalendar 中的事件点颜色

ios - "Initializer for conditional binding must have Optional type, not ' [字符串] '"

ios - 设置导航栏图标的大小 ios

ios - 大导航标题栏默认隐藏

ios - 应用程序加载器 - 您的 apple id 或密码输入错误 - iOS

c# - MonoTouch - 线程

ios - Localycs iOS 崩溃

ios - 在 TabBarController 中添加 View Controller 作为带有导航栏的 subview