Since setStatusBarHidden is deprecated, we will be using preferredStatusBarHidden in UIViewControllers
. But, how do I hide and show easily in a object class or custom UITableviewCell
class. We used to hide show using UIApplication
like this
[[UIApplication sharedApplication] setStatusBarHidden:YES];
Now it is deprecated and it can be used only in UIViewControllers
, is there a way to hide them in custom tableview cells and NSObject
classes?
答案 0 :(得分:1)
prefersStatusBarHidden
是UIViewController
对象而不是UIApplication
对象的方法。因此,您应该在UIViewController
上进行设置。这样。
- (BOOL)prefersStatusBarHidden {
return NO;
}
注意:
setNeedsStatusBarAppearanceUpdate
方法。childViewController
,要指定子视图控制器应控制首选状态栏的隐藏/未隐藏状态,请实施childViewControllerForStatusBarHidden
方法。如果要更动态地隐藏或显示状态栏
您可以应用这样的逻辑
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { shouldHideStatusBar = (shouldHideStatusBar)? NO: YES; [self setNeedsStatusBarAppearanceUpdate]; }
您也可以将此代码添加到按钮事件中
确保将添加到您的info.plist中的“基于视图控制器的状态栏外观”设置为YES,否则似乎无法正常工作。
答案 1 :(得分:0)
基本上,您只需要一个基本VC,您就可以在要控制状态栏的VC中对其进行子类化。 在其中,您将订阅给定的通知,该通知在发送时将控制VC的状态栏。
以下是代码:
extension Notification.Name {
static var statusBarShowHide: Notification.Name {
return .init(rawValue: "StatusBar.showHide")
}
}
class StatusBarControllableVC : UIViewController {
private var statusBarHidden = false
private func topViewController() -> UIViewController? {
var topController = UIApplication.shared.keyWindow?.rootViewController
while topController?.presentedViewController != nil {
topController = topController?.presentedViewController
}
return topController
}
override var prefersStatusBarHidden: Bool {
return statusBarHidden
}
@objc func statusBarShowHide(notification: NSNotification) {
guard let userInfo = notification.userInfo else {return}
let topController = topViewController()
if let hidden = userInfo["hidden"] as? Bool, self == topController {
statusBarHidden = hidden
self.setNeedsStatusBarAppearanceUpdate()
}
}
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(statusBarShowHide(notification:)), name: .statusBarShowHide, object: nil)
super.viewDidLoad()
}
}
现在,每当需要显示或隐藏状态栏时,您都将像这样发布通知:
NotificationCenter.default.post(name: .statusBarShowHide, object: nil, userInfo: ["hidden":true])
我相信这是最简单的方法。 在上面的代码中,我只显示/隐藏“顶部”视图控制器上的状态栏,但是显然您可以更改它