Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a custom view on the large title view of UINavigationBar introduced in iOS 11

Tags:

ios

swift

ios11

I want to add a custom subview on the large title view of UINavigationBar as App Store is doing in iOS 11. ("user icon" on right side)

We can access the traditional navigation bar area via UINavigationItem.titleView, but it seems that there is no API to access large title view area.

https://developer.apple.com/documentation/uikit/uinavigationitem/ https://developer.apple.com/documentation/uikit/uinavigationbar/

I confirmed the name is "_UINavigationBarLargeTitleView" using View Hierarchy Debugger. Can I add a custom view on it?

like image 791
Kazuhiro Hayashi Avatar asked Oct 07 '17 12:10

Kazuhiro Hayashi


1 Answers

Solution relying on the subview order of the large title label instead of its private class name, to keep it compliant with AppStore guidelines.

class CustomLargeTitleNavigationBar: UINavigationBar {

    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        if #available(iOS 11.0, *) {
            for subview in subviews {
                if let largeTitleLabel = subview.subviews.first(where: { $0 is UILabel }) as? UILabel {
                    let largeTitleView = subview
                    print("largeTitleView:", largeTitleView)
                    print("largeTitleLabel:", largeTitleLabel)
                    // you may customize the largeTitleView and largeTitleLabel here
                    break
                }
            }
        }
    }
}
like image 191
Cœur Avatar answered Sep 30 '22 14:09

Cœur