LoginSignup
4
1

More than 3 years have passed since last update.

iOS11にてNavigationBarButtonLeftの位置がおかしくなってしまう問題(swift)

Last updated at Posted at 2018-06-18

追記

iOS13対応版あげました

iOS13でもNavigationBarButtonの位置を調整したい - Qiita
https://qiita.com/rd0501/items/8e8254a23d87a9b2fea2

環境

Swift4ぐらい
Xcode Version 9.4 (9F1027a)

現象

iOS11にてNavigationBarButtonLeftの位置をdefaultの16の位置より外側に配置するために以下の処理を行ってました。
以下の実装を行うとNavigationBarButtonにdefaultで入る16ptの余白をなくすことができます。

import Foundation

final class BaseNavigationBar: UINavigationBar {

    override func layoutSubviews() {
        super.layoutSubviews()

        if #available(iOS 11, *) {
            loop: for view in subviews {
                for stack in view.subviews where stack is UIStackView {
                    stack.superview?.layoutMargins = .zero
                    break loop
                }
            }
        }

    }
}

final class BaseNavigationController: UINavigationController, UIGestureRecognizerDelegate {

    override init(rootViewController: UIViewController) {
        if #available(iOS 11, *) {
            super.init(navigationBarClass: BaseNavigationBar.self, toolbarClass: UIToolbar.self)
            self.viewControllers = [rootViewController]
        } else {
            super.init(rootViewController: rootViewController)
        }
    }
}

上記の対応を入れていたのに特定のViewControllerにてNavigationBarButtonの位置が16ptになってしまってました。

解決

self.navigationController?.setNavigationBarHidden(false, animated: true)とNavigationBarButtonを追加するタイミングを以下のように逆にしたらうまく行きました。

final class CommonWebViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.setNavigationBarHidden(false, animated: true)

        // NavigationBarLeftItemを追加する処理
        self.setNavLeftButton(type: .back, selector: #selector(CommonWebViewController.back(_:)))
    }
}

final class CommonWebViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // NavigationBarLeftItemを追加する処理
        self.setNavLeftButton(type: .back, selector: #selector(CommonWebViewController.back(_:)))
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

}
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1