ios - UIBarButtonItem(自定义 View :) -- not tappable

标签 ios swift uinavigationbar uibarbuttonitem

我在 viewDidLoad 中有以下内容。它设置了自定义 rightBarButtonItem(在自定义 UINavigationBar 中)。

    let button = UIButton()
    let attrs = [NSFontAttributeName: UIFont(name: "Montserrat-Light", size: 14)!, NSForegroundColorAttributeName: UIColor.black]
    let title = NSAttributedString(string: "Sign In", attributes: attrs)
    button.setAttributedTitle(title, for: .normal)
    button.addTarget(self, action: #selector(self.pushVcLogin), for: .touchUpInside)

    let parentView = UIView(frame: button.bounds)
    parentView.addSubview(button)
    button.sizeToFit()
    parentView.bounds = CGRect(x: 0, y: 0, width: button.bounds.size.width, height: button.bounds.size.height)

    self.navItem.rightBarButtonItem = UIBarButtonItem(customView: parentView)

自定义 UIBarButtonItem 看起来应该是这样,但它不可点击。

有什么想法吗?

最佳答案

首先,如果您的 View 层次结构具有 UINavigationController

其次,您可以使用 navigationItem 并在其上添加自定义 UIBarButtonItem。

我刚刚检查了以下代码,它有效。

    let button = UIButton()        
    let attrs = [NSFontAttributeName: UIFont(name: "Montserrat-Light", size: 14)!, NSForegroundColorAttributeName: UIColor.black]
    let title = NSAttributedString(string: "Sign In", attributes: attrs)
    button.setAttributedTitle(title, for: .normal)
    button.addTarget(self, action: #selector(self.pushVcLogin), for: .touchUpInside)

    let parentView = UIView(frame: button.bounds)
    parentView.addSubview(button)
    button.sizeToFit()
    parentView.bounds = CGRect(x: 0, y: 0, width: button.bounds.size.width, height: button.bounds.size.height)

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: parentView)

这也是 navigationController 和 viewController 的 Storyboard图像。

enter image description here

关于ios - UIBarButtonItem(自定义 View :) -- not tappable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45344908/

相关文章:

ios - 如何加载图像并根据它的方向 exif 数据旋转它并使用 UIImageOrientationUp exif 数据保存它

swift - 警告 : Attempt to Present ViewController on whose ViewController isn't in the view hierarchy (3D Touch)

ios - 消除 UINavigationBar 和 UIVisualEffectView 之间独特的模糊边缘

ios - 在 iOS 12 中更改 MFMailComposeViewController 中导航栏的标题颜色不起作用

ios - 在 Swift 中结合 CGBitmapInfo 和 CGI​​mageAlphaInfo

iOS:在处理每帧视频并用音频文件重写时收到内存警告

iphone - 如何在表格 View 上添加按钮作为附件?

ios - CALayer 蒙版周围的边框

ios - UIAlertView 显示警报显示晚于需要 ios

swift - UINavigationbar 的设置标题不起作用