简体   繁体   中英

custom titleView of navigationItem is not getting tapped on iOS 11

I am using a custom titleView and assigning it to navigationItem titleView. It had been working fine until iOS 11. Since the update it's position got misplaced to center as originally it was on more left. Beside that user interaction is not working.

titleView = Bundle.main.loadNibNamed("SomeNib", owner: self, options: nil)?.first as? SomeNib
navigationItem.titleView = titleView

titleView is just a usual nib.

then for enabling interaction:

if let titleView = self.navigationItem.titleView {
            let tap = UITapGestureRecognizer(target: self, action: #selector(onTitleViewTap))
            titleView.addGestureRecognizer(tap)
            titleView.isUserInteractionEnabled = true
        }

In iOS 11, titleView is getting set with Autolayout. Hence, the size of the titleView is the intrinsic size of the view you are setting in titleView.

This code in your view class(which you are setting as titleView) should help:

override var intrinsicContentSize: CGSize {
    return UILayoutFittingExpandedSize
} 

I have a created a Custom UIView with xib. Inside the UIView, I added UILabel , ImageView and a UIButton on top. On click on Hidden button I am able to call the click event.

在此处输入图片说明

import UIKit

    class NavBarTitleView: UIView {

        @IBOutlet weak var title : UILabel!
        @IBOutlet weak var clickButton: UIButton!
        
        /// Create an instance of the class from its .xib
        class func instanceFromNib() -> NavBarTitleView {
            return UINib(nibName: "NavBarTitleView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! NavBarTitleView
        }
        
        //this line of code will help to enable a click event.
        override var intrinsicContentSize: CGSize {
            return UIView.layoutFittingExpandedSize
        }
    }

Then in UIViewcontroler, I added the below code.

    if let title = self.navBarTitle{
        if navbarTitleView == nil {
            navbarTitleView = NavBarTitleView.instanceFromNib()
            self.navigationItem.titleView = navbarTitleView
        }
        navbarTitleView!.title.text = title
        navbarTitleView!.clickButton.addTarget(self, action: #selector(didTapNavbarTitle(_:)), for: .touchUpInside)
        navbarTitleView!.layoutIfNeeded()
        
    }else{
        navigationItem.title = ""
    }

Button action:

@objc func didTapNavbarTitle(_ sender: Any){
    print("NavBar Selected")
}

Result - 在此处输入图片说明

I hope this will work. Tested on code 11.6 and os version 13.6

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