【问题标题】:custom titleView of navigationItem is not getting tapped on iOS 11在 iOS 11 上未点击 navigationItem 的自定义 titleView
【发布时间】:2017-09-28 05:07:07
【问题描述】:

我正在使用自定义 titleView 并将其分配给 navigationItem titleView。在 iOS 11 之前它一直运行良好。自从更新以来,它的位置错位到中心,因为它最初位于更左侧。除此之外,用户交互不起作用。

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

titleView 只是一个普通的 nib。

然后用于启用交互:

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

【问题讨论】:

    标签: ios swift3 ios11


    【解决方案1】:

    在 iOS 11 中,titleView 设置为自动布局。因此,titleView 的大小是您在 titleView 中设置的视图的固有大小。

    您的视图类中的这段代码(您将其设置为 titleView)应该会有所帮助:

    override var intrinsicContentSize: CGSize {
        return UILayoutFittingExpandedSize
    } 
    

    【讨论】:

    【解决方案2】:

    我用 xib 创建了一个自定义 UIView。在 UIView 内部,我在顶部添加了 UILabelImageViewUIButton。单击隐藏按钮时,我可以调用单击事件。

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

    然后在 UIViewcontroler 中,我添加了以下代码。

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

    按钮操作:

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

    结果 -

    我希望这会奏效。在代码 11.6 和操作系统版本 13.6 上测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 2018-03-16
      相关资源
      最近更新 更多