无法更改标题导航控制器

时间:2017-01-24 19:23:10

标签: ios swift uinavigationcontroller

我无法在选项视图中更改导航栏的标题。我没有使用Storyboard。我也无法添加按钮。

这是我的App代理代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let viewController = MenuTableViewController(nibName: nil, bundle: nil) //ViewController = Name of your controller
    let navigationController = UINavigationController(rootViewController: viewController)

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()
    return true
}

这是我的MenuTabeViewController文件

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Options", style: .plain, target: self, action: #selector(handleOptions))
}

func handleOptions() {
    let optionViewController = optionsViewController()
    present(optionViewController, animated: true, completion: nil)
}

这是我的选项文件

class optionsViewController: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()
    view?.backgroundColor = UIColor.white
    //I've tried 3 solutions
    self.navigationItem.title = "Options"
    self.title = "Options"
    self.navigationBar.topItem?.title = "Options"
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    dismiss(animated: true, completion: nil)
}

}

1 个答案:

答案 0 :(得分:0)

我认为问题是由于您在展示时没有正确设置新的导航/视图控制器。

在展示新的UINavigationController时,就像您之前在AppDelegate中所做的那样,您需要创建UIViewController并将其设置为rootViewController。因此,您需要OptionsNavControllerOptionsViewController之类的内容,而不是单个导航控制器。

然后在OptionsViewController简单电话self.title = @"Options"

修改

我在下面举了一个例子。

func handleOptions() {
    let optionsViewController = OptionsViewController()
    let optionsNavController = UINavigationController(rootViewController: optionsViewController)
    present(optionsNavController, animated: true, completion: nil)
}

然后如上所述,请在self.title = @"Options"中致电OptionsViewController