仅更改 UITableView 的主体颜色或仅更改状态栏颜色

Changing only the body colour of UITableView or changing only the status bar colour

我想为 iOS 状态栏设置特定的颜色,我知道它将采用顶视图控制器视图的颜色。 因此,我可以通过将我想要的状态栏颜色应用到 table 视图来获得它,它看起来像这样

但是当它没有任何行时,整个 table 视图都会得到那种颜色(很明显!但这不是我想要的)

有没有办法只给 table 视图的顶部颜色,以便状态栏获得那种颜色,或者我可以单独更改状态栏颜色。 我有

View controller-based status bar appearance

在 Info.plist 作为 NO .

您应该使用一个自定义视图代替状态栏,并为该视图提供背景颜色。并将您的表格视图置于此自定义视图的正下方,这样您就不需要在表格视图的上部设置颜色!

视图的高度应为 20,宽度应等于屏幕宽度。

位置应为 (0,0)。

希望这会有所帮助:)

您可以将背景颜色应用到状态栏,如下所示

UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
    statusBar.backgroundColor = [UIColor redColor];
}

在 AppDelegate didFinishLaunchingWithOptions 方法中使用上述代码将更改整个应用程序的状态栏背景颜色。如果您想将背景颜色更改为特定的视图控制器,那么您应该遵循 @Lion's 方法。

希望对您有所帮助。

您还可以添加一个 window 到顶部状态栏并更改其颜色。它看起来像这样:

// AppDelegate.Swift
let topWindow = UIWindow(frame: CGRect(....))
topWindow.backgroundColor = ...
window.addSubview(topWindow)

在 Swift:

override func viewWillAppear(animated: Bool) {
    self.navigationController?.navigationBarHidden =  true

UIApplication.sharedApplication().statusBarHidden = false
UIApplication.sharedApplication().statusBarStyle = .LightContent

let statusBar: UIView = UIApplication.sharedApplication().valueForKey("statusBar") as! UIView
if statusBar.respondsToSelector("setBackgroundColor:") {
    statusBar.backgroundColor = UIColor.redColor()
}

}