代码之家  ›  专栏  ›  技术社区  ›  Witterquick

刷新导航栏背景色

  •  0
  • Witterquick  · 技术社区  · 6 年前

    我有一个与视图背景颜色相同的导航栏。 如果用户按下按钮,视图的颜色会改变,但导航栏的颜色不会改变。 如果我试图手动更改,请使用

    self.navigationController?.navigationBar.barTintColor = UIColor(red: 104.0/255.0, green: 154.0/255.0, blue: 26.0/255.0, alpha: 1.0)
    

    它确实会更改导航栏的背景颜色,但它与视图的颜色并不完全相同,即使我为背景设置了相同的值。

    如何将导航栏的颜色设置为与视图的颜色相同?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Sid Mhatre puja    6 年前

    导航栏与ViewController中的不同之处在于,导航栏是半透明的,系统将为导航栏应用默认的alpha值。

    self.navigationController?.navigationBar.isTranslucent = false
    self.navigationController?.navigationBar.barTintColor = UIColor(red: 104.0/255.0, green: 154.0/255.0, blue: 26.0/255.0, alpha: 1.0)
    

    或手动:

    导航栏和ViewController背景颜色的差异为20。这使UINavigationBar具有“光泽”外观,因此具有内置样式。

    因此,R=104 | G=154 | B=26将变为R=84 | G=134 B | B=6。

    navigationController?.navigationBar.barTintColor = UIColor(red: 84.0/255.0, green: 134.0/255.0, blue: 6.0/255.0, alpha: 1.0)
    self.view.backgroundColor = UIColor(red: 104.0/255.0, green: 154.0/255.0, blue: 26.0/255.0, alpha: 26.0)
    
        2
  •  1
  •   frin    6 年前

    有两种方法:

    1) 将导航栏设置为非半透明:

    navigationController?.navigationBar.barTintColor = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0)
    navigationController?.navigationBar.isTranslucent = false
    

    2) 设置导航栏的背景图像:

    navigationController?.navigationBar.setBackgroundImage(UIImage(named: "red"), for: .default)
    

    您还可以使用以下函数提供基于UIColor生成的UIImage:

    func convertUIColorToUIImage(_ color: UIColor, size: CGSize) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }