简体   繁体   中英

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

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?

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
                }
            }
        }
    }
}

I guess it should be more or less like that, based on this article. https://qiita.com/KikurageChan/items/4152c2d8ac89c601a054

import UIKit
@IBDesignable class CustomNavigationBar: UINavigationBar {
override func layoutSubviews() {
    super.layoutSubviews()
    if #available(iOS 11.0, *) {
        for subview in self.subviews {
            let stringFromClass = NSStringFromClass(subview.classForCoder)
            if stringFromClass.contains("UINavigationBarLargeTitleView") {
                //subview.frame.size.height = 30
                // Custom view
                subview.addSub.....

            }
        }
    }
  }
}

CustomNavigationBar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM