简体   繁体   English

仅在显示导航控制器的最顶部页面时才使UINavigationBar透明吗?

[英]Make a UINavigationBar transparent only when the topmost page of navigation controller is shown?

I have created a custom subclass of UINavigationController that has a fully transparent background, with this code in the custom class: 我创建了一个UINavigationController的自定义子类,该子类具有完全透明的背景,并且该代码位于自定义类中:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
    self.navigationBar.shadowImage = UIImage()
    self.navigationBar.translucent = true        
}

I'd like to show a semi-transparent background on the navigation bar on subsequent screens in the navigation, for example underneath the back button in a detail view. 我想在导航的后续屏幕上的导航栏上显示半透明的背景,例如在详细视图中的“后退”按钮下方。 I've added the following line to the above code to create the appearance I want: 我在上面的代码中添加了以下行以创建所需的外观:

self.navigationBar.backgroundColor = UIColorFromHex(0xFFFFFF, alpha: 0.8)

UIColorFromHex is a helper function to generate UIColors. UIColorFromHex是用于生成UIColors的辅助函数。

func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
    let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
    let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
    let blue = CGFloat(rgbValue & 0xFF)/256.0

    return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}

So far, I can only make the navigation bar is transparent for all screens, or semi-transparent for all screens. 到目前为止,我只能使导航栏对于所有屏幕都是透明的,或者对于所有屏幕都是半透明的。

Is there a way to toggle the appearance between transparent and semi-transparent when the root screen in the navigation stack is presented? 当显示导航堆栈中的根屏幕时,是否可以在透明和半透明之间切换外观?

Try this. 尝试这个。

if let rootViewController = self.navigationController.viewControllers[0] as? YourClassName {
    //Code for transparent bar
} else {
   //Code for simple bar

}

Try this in viewWillAppear method of every class, where YourClassName will be the respective class name in which you put check.. Or create a separate method and call it as necessary. 在每个类的viewWillAppear方法中尝试使用此方法,其中YourClassName将是您要在其中进行检查的相应类名。或者创建一个单独的方法并根据需要调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM