我正在制作一个cocoa lib,我需要获取状态栏高度,我使用这段代码:
let statusBarHeight = UIApplication.shared.isStatusBarHidden ? CGFloat(0) : UIApplication.shared.statusBarFrame.height
我在另一个项目中使用lib,一切正常,但如果我在app扩展中使用Lib,我会获得:
'shared' is unavailable: Use view controller based solutions where appropriate instead
如何测试我是否在扩展内?或者如何在不使用共享的情况下获得状态高度?
谢谢!
答案 0 :(得分:1)
如果您的目标是iOS 11,请使用视图控制器的topLayoutGuide.length
或视图控制器的视图safeAreaInsets.top
。这些值也会考虑任何导航栏。
答案 1 :(得分:0)
我使用这个解决方案:
extension UIViewController{
/// Calculate top distance with "navigationBar" and "statusBar" by adding a
/// subview constraint to navigationBar or to topAnchor or superview
/// - Returns: The real distance between topViewController and Bottom navigationBar
func calculateTopDistance() -> CGFloat{
/// Create view for misure
let misureView : UIView = UIView()
misureView.backgroundColor = .clear
view.addSubview(misureView)
/// Add needed constraint
misureView.translatesAutoresizingMaskIntoConstraints = false
misureView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
misureView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
misureView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
if let nav = navigationController {
misureView.topAnchor.constraint(equalTo: nav.navigationBar.bottomAnchor).isActive = true
}else{
misureView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
}
/// Force layout
view.layoutIfNeeded()
/// Calculate distance
let distance = view.frame.size.height - misureView.frame.size.height
/// Remove from superview
misureView.removeFromSuperview()
return distance
}
}
我写了一篇关于媒体的文章,在这里:
答案 2 :(得分:-2)
试试这个
let statusBarHeight = Util.statusBarHeight()
class Util: NSObject {
class func statusBarHeight() -> CGFloat {
return UIApplication.shared.isStatusBarHidden ? CGFloat(0) :
UIApplication.shared.statusBarFrame.height
}
}
我总是按照上述方法访问全局UI元素,例如方向,状态栏高度等。