带有自定义 UIButton 的 UIBarButtonItem 在 iOS <= 10 时不可见

UIBarButtonItem with custom UIButton is invisible on iOS <= 10

我需要在 navigationController 的左侧为我的应用程序创建一个 "burger menu" 按钮,但是由于 NavCon 是透明的,我需要在我的图标上有一个阴影。

因此,我创建了一个带有图像、投影的自定义 UIButton,并将其添加为 UIBarButtonItem 上的自定义视图,如下所示:

let menuButton = UIButton(type: .custom)
menuButton.addTarget(self, action: #selector(showSideMenu), for: .touchUpInside)
menuButton.setImage(#imageLiteral(resourceName: "menu_white"), for: .normal)
menuButton.tintColor = UIColor.white
menuButton.layer.masksToBounds = false
menuButton.layer.shadowColor = UIColor.black.cgColor
menuButton.layer.shadowOpacity = 1.0
menuButton.layer.shadowRadius = 5
menuButton.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)

self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: menuButton)

上面的代码在 iOS 11 上工作得很好,但是当我在 ios 9 和 10(模拟器和真实设备)上测试我的应用程序时,菜单图标是不可见的。它可以点击并按预期工作,但没有可见的图标。

在 View Hierarchy Debugger 中,我可以看到一个宽度和高度为 0 的 UIButton,而在 ios11 中,我可以看到带有嵌入式 UIButton 的普通 UIButtonBarStackview。

关于如何解决这个问题以及为什么会发生这种情况有什么想法吗?非常感谢!

请提及按钮框架

 let menuButton =  UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 40))

可能对你有帮助谢谢

您只需调用 menuButton.sizeToFit() 即可。