swift - 从另一个 Swift 类访问 navigationItem.title

标签 swift uinavigationcontroller uinavigationitem

如何从单独的类访问导航 Controller 内的标题?我通过 Storyboard将我的 mainVC 嵌入到导航 Controller 中。我可以从同一个类的 viewDidLoad 内部访问标题,就像这样 self.navigationItem.title = "MyTitle"。但是,我需要从单独的类 'CustomNavigation 访问标题,如下所示:

class: CustomNavigation: UIViewController() {
   override func viewDidLoad(){
      super.viewDidLoad()

      func createCustomNav(){

         self.navigationItem.title = "MyTitle"
      }

   }

}

不幸的是,它不起作用。我也尝试过这个:

func createCustomNav(){

   let nav = UINavigationBar()
   let title = UINavigationItem(title: "MyTitle")
   nav.setItems([title], animated: false)
   self.view.addSubview(nav)
}

这也不起作用。我没有收到任何错误。

我在 mainVC 中实例化 CustomNavigation: var customNavigation = CustomNavigation()

任何帮助将不胜感激!

最佳答案

建立一个协议(protocol)来描述您想要完成的工作。

protocol NavigationTitler {
    func updateTitle(with title: String)
}

定义您的类将如何使用该协议(protocol)。

class CustomNavigation: UINavigationController {
    var titleDelegate: NavigationTitler?
    func work() {
        if let del = titleDelegate {
            del.updateTitle(with: "Title from other object")
        }
    }
}

实现协议(protocol)(这是针对您的mainVC)。

class ViewController: UIViewController, NavigationTitler {
    var customNavigation: CustomNavigation?
    func updateTitle(with title: String) {
        self.navigationItem.title = title
    }
    func buildCustomController() {
        customNavigation = CustomNavigation()
        customNavigation!.titleDelegate = self
    }
}

关于swift - 从另一个 Swift 类访问 navigationItem.title,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59796226/

相关文章:

ios - 无法转换 UINavigationController 类型的值

ios - 导航 Controller subview 中的导航栏初始化到错误的位置(即使它自行修复)

ios - UINavigationItem 提示问题

iphone - 如何获得全尺寸的 UINavigationBar titleView

ios - 减少 UINavigationBar 中条形按钮项之间的空白

swift - 为什么在此示例中使用强制展开?

ios - tableview 方法的问题 func tableView(tableView : UITableView, editActionsForRowAtIndexPath indexPath : NSIndexPath) -> [UITableViewRowAction]?

iphone - 导航项未出现在 View Controller 上

json - updateSearchResultsForSearchController JSON

ios - 展开可选值时为零,但在打印期间该值存在