如何使UINavigationBar透明?虽然我希望它的栏项仍然可见。
当前回答
如果你使用最新的测试版iOS 13.4和Xcode 11.4进行构建,那么接受的答案将不再适用。 我找到了另一种方法,也许这只是测试版软件中的一个bug,但我把它写下来了,以防万一
(5)迅速
import UIKit
class TransparentNavBar :UINavigationBar {
override func awakeFromNib() {
super.awakeFromNib()
self.setBackgroundImage(UIImage(), for: .default)
self.shadowImage = UIImage()
self.isTranslucent = true
self.backgroundColor = .clear
if #available(iOS 13.0, *) {
self.standardAppearance.backgroundColor = .clear
self.standardAppearance.backgroundEffect = .none
self.standardAppearance.shadowColor = .clear
}
}
}
其他回答
解决方案- Swift 5 - iOS 13+
根据文档,在你的UIViewController子类中:
override func viewDidLoad()
{
super.viewDidLoad()
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
//appearance.backgroundColor = UIColor.clear
navigationItem.compactAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
navigationItem.standardAppearance = appearance
//...
}
只是为了澄清,这使得UINavigationBar完全透明。栏按钮项仍然可见,并正常工作。
什么不起作用
override func viewDidLoad()
{
super.viewDidLoad()
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.isOpaque = false
//...
}
这让我意识到我其实不知道透明RIP和半透明RIP之间的区别。
参考文献
https://developer.apple.com/documentation/uikit/uinavigationcontroller/customizing_your_app_s_navigation_bar
https://www.lexico.com/en/definition/transparent
https://www.lexico.com/en/definition/translucent
更新08/10/2021
在以我提供的方式设置外观后,更改navigationItem栏按钮将重置外观,您必须再次执行此操作。
试试下面这段代码:
self.navigationController.navigationBar.translucent = YES;
这似乎很有效:
@implementation UINavigationBar (custom)
- (void)drawRect:(CGRect)rect {}
@end
navigationController.navigationBar.backgroundColor = [UIColor clearColor];
另一种方式,为我工作是子类UINavigationBar和留下drawRect方法空!!
@IBDesignable class MONavigationBar: UINavigationBar {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}}
在按照上面大家说的去做之后,也就是:
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true
... 我的导航栏还是白色的。所以我加了这一行:
navigationController?.navigationBar.backgroundColor = .clear
... 果不其然!这似乎奏效了。
推荐文章
- 保留HTML字体大小时,iPhone的方向从纵向改变为横向
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?