问题
I am trying to add custom view to NavigationBar and result not working correct.
public let statusBarHeight: CGFloat = {
var heightToReturn: CGFloat = 0.0
for window in UIApplication.shared.windows {
if let height = window.windowScene?.statusBarManager?.statusBarFrame.height, height > heightToReturn {
heightToReturn = height
}
}
return heightToReturn
}()
override func viewDidLoad() {
super.viewDidLoad()
// self.navigationController?.navigationBar.isHidden = true
// Do any additional setup after loading the view.
let barView = UIView(frame: CGRect.zero)
barView.backgroundColor = .purple
barView.translatesAutoresizingMaskIntoConstraints = false
if let navBarSize = self.navigationController?.navigationBar.frame.size {
// barView.frame.size = CGSize(width: navBarSize.width, height: navBarSize.height + statusBarHeight)
self.navigationController?.navigationBar.subviews.first?.insertSubview(barView, at: 0)
NSLayoutConstraint.activate([
barView.leadingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.leadingAnchor)!),
barView.trailingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.trailingAnchor)!),
barView.heightAnchor.constraint(equalToConstant: navBarSize.height + statusBarHeight )
])
}
}
See the difference in notch device this:
回答1:
I have to make a change in your code, now it's work on all devices even iPhone 12 mini as shown in the image. check image
override func viewDidLoad() {
super.viewDidLoad()
let barView = UIView(frame: CGRect.zero)
barView.backgroundColor = .purple
barView.translatesAutoresizingMaskIntoConstraints = false
if (self.navigationController?.navigationBar.frame.size) != nil {
self.navigationController?.navigationBar.subviews.first?.insertSubview(barView, at: 0)
NSLayoutConstraint.activate([
barView.leadingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.leadingAnchor)!),
barView.trailingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.trailingAnchor)!),
barView.topAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.topAnchor)!),
barView.bottomAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.bottomAnchor)!),
])
}
}
来源:https://stackoverflow.com/questions/65103209/adding-custom-view-into-navigationbar-not-working