Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align UINavigationBar title with button on the right like iOS13 Messages app

What is the best way to align right bar button items with left title in UINavigationBar ? (now I have the icons at the top right corner)

like image 704
Zac Avatar asked Nov 16 '22 03:11

Zac


1 Answers

maybe there is a more correct and optimal solution, but it is suitable for me. Do not be alarmed by the syntax, I use SnapKit

  1. Create button or view
lazy private var settingsButton = UIButton().then {
        $0.setImage(Image.settings, for: .normal)
    }
  1. override viewDidAppear(_ animated: Bool)
navigationController?.navigationBar.subviews.forEach { subview in
    let stringFromClass = NSStringFromClass(subview.classForCoder)
    guard stringFromClass.contains("UINavigationBarLargeTitleView") else { return }
    subview.subviews.forEach { label in
        guard label is UILabel else { return }
        subview.addSubview(settingsButton)
        settingsButton.snp.makeConstraints{
            $0.top.equalTo(label)
            $0.right.equalToSuperview().offset(-14)
            $0.height.width.equalTo(35)
        }
    }
}

  1. set UIScrollViewDelegate and in scrollViewDidScroll method get ahead of the navigationBar state and then hide / show the UIBarButtonItem

Result

screenshot

like image 81
Alexandr Guzenko Avatar answered May 26 '23 20:05

Alexandr Guzenko