【问题标题】:Were to call method to change appearance of navigation bar? Swift 3是调用方法来改变导航栏的外观吗?斯威夫特 3
【发布时间】:2017-05-21 11:16:52
【问题描述】:

我在 UINavigationController 中嵌入了几个视图控制器。我想为每个 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)
  }
}

【问题讨论】:

  • 使用有助于设置navBar 标题的方法创建协议。在每个 VC 中实现协议并调用 viewDidLoad 中的方法。您可以向此方法添加默认实现以设置默认标题。

标签: ios swift3 uinavigationbar


【解决方案1】:

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

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

}

【讨论】:

    【解决方案2】:

    你可以打电话

    navigationItem.title = "你的标题"

    在 viewDidLoad 中。

    【讨论】:

    • 我的应用程序中有 30 多个 viewController,并且 title 变量将具有更多属性,这意味着如果我编写相同的代码 30 次而不是函数调用,它将增加代码库。
    • 您甚至可以在 prepareForSegue 中调用它,这应该可以帮助您减少代码库
    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多