是否调用方法改变导航栏的外观?斯威夫特3

时间:2017-05-21 11:16:52

标签: ios swift3 uinavigationbar

我在UINavigationController中嵌入了几个viewcontroller。我想为每个viewController自定义导航栏标题的外观。调用setCustomTitleInNavBar的最佳方法是什么?如果在viewDidLoad中调用它,则self尚未初始化,应用程序将崩溃。在ViewWillAppear中,当向用户显示视图时,尚未显示标题。如果这不是正确的方法,请告知替代实施。

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)
  }
}

2 个答案:

答案 0 :(得分:2)

以下是通过协议实现它的方法:

// 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")
    }

}

答案 1 :(得分:1)

你可以打电话

  

navigationItem.title ="您的标题"

在viewDidLoad中