使用Swift自定义iOS中的导航栏

更改导航栏颜色

  • 为了更改所有视图控制器的导航栏颜色,必须在AppDelegate.swift文件中进行设置
  • 将以下代码添加到didFinishLaunchingWithOptions函数中
 var navigationBarAppearace = UINavigationBar.appearance() 
 navigationBarAppearace.tintColor = uicolorFromHex(0xffffff) 
navigationBarAppearace.barTintColor = uicolorFromHex(0x034517)
  • 在这里tintColor属性更改导航栏的背景颜色
  • barTintColor属性影响颜色
  1. 后指示器图像
  2. 按钮标题
  3. 按钮图片
  • 此代码不会影响导航栏标题的颜色。 它仍然保持黑色

更改导航栏标题的颜色

  • 将以下代码添加到didFinishLaunchingWithOptions函数中
 var navigationBarAppearace = UINavigationBar.appearance() 
 navigationBarAppearace.tintColor = uicolorFromHex(0xffffff) 
navigationBarAppearace.barTintColor = uicolorFromHex(0x034517)
 // change navigation item title color 
navigationBarAppearace.titleTextAttributes =[NSForegroundColorAttributeName:UIColor.whiteColor()]
  • titleTextAttributes影响标题文本,在这里我将标题文本设置为白色

以编程方式更改导航栏标题

  • 为了更改导航项的标题(在ViewController中),您必须在ViewController的viewDidLoad函数中设置标题
 override func viewDidLoad() { 
super.viewDidLoad()
  self.navigationItem.title = "New title" 
}
  • 以下是此更改后的示例输出

更改状态栏颜色

  • 在上面的示例中,状态栏颜色为黑色
  • 为了更改状态栏的颜色,我们做了两个更改
  • 首先在info.plist文件中定义view controller-based status bar属性(将其设置为NO
  • 如果通过vim打开它( vim /info.plist ),则可以看到它包含一个属性调用UIViewControllerBasedStatusBarAppearance ,其false
  • 然后在AppDelegate.swift中的didFinishLaunchingWithOptions函数中定义状态栏的颜色(这将影响您应用中的所有视图控制器,因为它是在AppDelegate.swift中定义的)
 UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent 

以十六进制值定义颜色

  • 在上面的代码中,我定义了一个自定义函数来将颜色定义为hex
 func uicolorFromHex(rgbValue:UInt32)->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:1.0) 
}
  • 此函数将十六进制值转换为UIColor (带有红色,绿色和蓝色)