如果互联网连接,我想更改设备状态栏的颜色,而不是状态栏颜色应变为黑色,如果未连接互联网,则颜色或状态栏应变为红色,以便指示在使用 SWIFT 的应用程序期间,互联网是否正常工作......帮帮我
在Info.plist
中,您需要将"基于视图控制器的状态栏外观"设置为布尔值。
如果将其设置为 YES
则应覆盖每个视图控制器中的preferredStatusBarStyle
函数。
如果将其设置为 NO
则可以使用以下命令在AppDelegate
中设置样式:
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = true
//Status bar style and visibility
UIApplication.sharedApplication().statusBarHidden = false
UIApplication.sharedApplication().statusBarStyle = .LightContent
//Change status bar color
let statusBar: UIView = UIApplication.sharedApplication().valueForKey("statusBar") as! UIView
if statusBar.respondsToSelector("setBackgroundColor:") {
statusBar.backgroundColor = UIColor.redColor()
}
}
在 Swift 和 iOS9 中测试
如果使用导航控制器,请将以下内容放在视图控制器类中:
override func viewDidLoad(){
...
self.navigationController?.navigationBar.barStyle = .Black
}
否则,请覆盖 UIViewController 中的preferredStatusBarStyle()
:
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
您可以在此处找到更多信息
对于 Swift 2.3
尝试使用这些方法
// Get network status
class func hasConnectivity() -> Bool {
let reachability: Reachability = Reachability.reachabilityForInternetConnection()
let networkStatus: Int = reachability.currentReachabilityStatus().value
return networkStatus != 0
}
// change status bar color
var navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.tintColor = UIColor.blueColor()
navigationBarAppearace.barTintColor = UIColor.blueColor()
tintColor
属性更改导航栏的背景颜色
barTintColor
属性对颜色的影响
但是,如果您想在运行时更改状态栏颜色,我认为更好的方法是在状态栏后面添加一个视图。
对于 Swift 3
这应该适用于Xcode 8和Swift 3
。override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@rckoenes评论的那样,从iOS 7开始,状态栏会绘制在您的应用程序上。因此,您可以将视图放在状态栏区域后面(从顶部 20px - 状态栏的高度),并可以根据互联网连接状态的变化控制其背景颜色,没有其他选项可以更改状态栏颜色。
//在你的 AppDelegate 中.swift 在 didFinishLaunchingWithOptions 中: UINavigationBar.appearance().barTintColor = UIColor.greenColor()
//Optionally, if you need a specific color, how you do it with RGB:
UINavigationBar.appearance().barTintColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
or
在 Info.plist 中,您需要将"基于视图控制器的状态栏外观"设置为布尔值。
UIApplication.sharedApplication().statusBarStyle = .LightContent
要在黑色状态栏中显示白色文本: 在 Info.plist 中将基于视图控制器的状态栏外观切换为 NO在"应用程序代表"中.swift添加 let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
statusBar.backgroundColor = UIColor.black
in didFinishLaunchingWithOptions
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)