iOS 11 导航栏高度自定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44387285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS 11 navigation bar height customizing
提问by Максим Котляр
Now in iOS 11, the sizeThatFits
method is not called from UINavigationBar
subclasses. Changing the frame of UINavigationBar
causes glitches and wrong insets.
So, any ideas how to customize navbar height now?
现在在 iOS 11 中,sizeThatFits
不会从UINavigationBar
子类调用该方法。更改UINavigationBar
导致故障和错误插图的框架。那么,现在如何自定义导航栏高度的任何想法?
回答by frangulyan
According to Apple developers (look here, hereand here), changing navigation bar height in iOS 11 is not supported. Herethey suggest to do workarounds like having a view under the navigation bar (but outside of it) and then remove the nav bar border. As a result, you will have this in storyboard:
根据 Apple 开发人员的说法(查看此处、此处和此处),不支持在 iOS 11 中更改导航栏高度。在这里,他们建议采取变通方法,例如在导航栏下方(但在导航栏之外)有一个视图,然后移除导航栏边框。因此,您将在情节提要中看到以下内容:
look like this on the device:
在设备上看起来像这样:
Now you can do a workaround that was suggested in the other answers: create a custom subclass of UINavigationBar
, add your custom large subview to it, override sizeThatFits
and layoutSubviews
, then set additionalSafeAreaInsets.top
for the navigation's top controller to the difference customHeight - 44px
, but the bar view will still be the default 44px, even though visually everything will look perfect. I didn't try overriding setFrame
, maybe it works, however, as Apple developer wrote in one of the links above: "...and neither is [supported] changing the frame of a navigation bar that is owned by a UINavigationController (the navigation controller will happily stomp on your frame changes whenever it deems fit to do so)."
现在,您可以执行其他答案中建议的解决方法:创建 的自定义子类UINavigationBar
,向其中添加自定义大子视图,覆盖sizeThatFits
和layoutSubviews
,然后将additionalSafeAreaInsets.top
导航的顶部控制器设置为差异customHeight - 44px
,但条形视图仍将是默认 44px,即使在视觉上一切看起来都很完美。我没有尝试覆盖setFrame
,也许它可以工作,但是,正如 Apple 开发人员在上面的链接之一中所写的那样:“……而且 [支持] 更改 UINavigationController 拥有的导航栏的框架(导航只要控制器认为合适,它就会很高兴地踩踏您的框架更改)。”
In my case the above workaround made views to look like this (debug view to show borders):
在我的情况下,上述解决方法使视图看起来像这样(显示边框的调试视图):
As you can see, the visual appearance is quite good, the additionalSafeAreaInsets
correctly pushed the content down, the big navigation bar is visible, however I have a custom button in this bar and only the area that goes under the standard 44 pixel nav bar is clickable (green area in the image). Touches below the standard navigation bar height doesn't reach my custom subview, so I need the navigation bar itself to be resized, which the Apple developers say is not supported.
如您所见,视觉外观非常好,additionalSafeAreaInsets
正确按下内容,大导航栏可见,但是我在这个栏中有一个自定义按钮,只有标准44像素导航栏下方的区域是可点击的(图像中的绿色区域)。低于标准导航栏高度的触摸不会到达我的自定义子视图,因此我需要调整导航栏本身的大小,Apple 开发人员表示不支持。
回答by Shawn Baek
Updated 07 Jan 2018
2018 年 1 月 7 日更新
This code is support XCode 9.2, iOS 11.2
此代码支持 XCode 9.2、iOS 11.2
I had the same problem. Below is my solution. I assume that height size is 66.
我有同样的问题。下面是我的解决方案。我假设高度大小为 66。
Please choose my answer if it helps you.
如果对您有帮助,请选择我的答案。
Create CINavgationBar.swift
创建 CINavgationBar.swift
import UIKit
@IBDesignable
class CINavigationBar: UINavigationBar {
//set NavigationBar's height
@IBInspectable var customHeight : CGFloat = 66
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: customHeight)
}
override func layoutSubviews() {
super.layoutSubviews()
print("It called")
self.tintColor = .black
self.backgroundColor = .red
for subview in self.subviews {
var stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("UIBarBackground") {
subview.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: customHeight)
subview.backgroundColor = .green
subview.sizeToFit()
}
stringFromClass = NSStringFromClass(subview.classForCoder)
//Can't set height of the UINavigationBarContentView
if stringFromClass.contains("UINavigationBarContentView") {
//Set Center Y
let centerY = (customHeight - subview.frame.height) / 2.0
subview.frame = CGRect(x: 0, y: centerY, width: self.frame.width, height: subview.frame.height)
subview.backgroundColor = .yellow
subview.sizeToFit()
}
}
}
}
Set Storyboard
设置故事板
Set Custom NavigationBar class
设置自定义 NavigationBar 类
Add TestView + Set SafeArea
添加 TestView + 设置 SafeArea
ViewController.swift
视图控制器.swift
import UIKit
class ViewController: UIViewController {
var navbar : UINavigationBar!
@IBOutlet weak var testView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//update NavigationBar's frame
self.navigationController?.navigationBar.sizeToFit()
print("NavigationBar Frame : \(String(describing: self.navigationController!.navigationBar.frame))")
}
//Hide Statusbar
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(false)
//Important!
if #available(iOS 11.0, *) {
//Default NavigationBar Height is 44. Custom NavigationBar Height is 66. So We should set additionalSafeAreaInsets to 66-44 = 22
self.additionalSafeAreaInsets.top = 22
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
SecondViewController.swift
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Create BackButton
var backButton: UIBarButtonItem!
let backImage = imageFromText("Back", font: UIFont.systemFont(ofSize: 16), maxWidth: 1000, color:UIColor.white)
backButton = UIBarButtonItem(image: backImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(SecondViewController.back(_:)))
self.navigationItem.leftBarButtonItem = backButton
self.navigationItem.leftBarButtonItem?.setBackgroundVerticalPositionAdjustment(-10, for: UIBarMetrics.default)
}
override var prefersStatusBarHidden: Bool {
return true
}
@objc func back(_ sender: UITabBarItem){
self.navigationController?.popViewController(animated: true)
}
//Helper Function : Get String CGSize
func sizeOfAttributeString(_ str: NSAttributedString, maxWidth: CGFloat) -> CGSize {
let size = str.boundingRect(with: CGSize(width: maxWidth, height: 1000), options:(NSStringDrawingOptions.usesLineFragmentOrigin), context:nil).size
return size
}
//Helper Function : Convert String to UIImage
func imageFromText(_ text:NSString, font:UIFont, maxWidth:CGFloat, color:UIColor) -> UIImage
{
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.byWordWrapping
paragraph.alignment = .center // potentially this can be an input param too, but i guess in most use cases we want center align
let attributedString = NSAttributedString(string: text as String, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.paragraphStyle:paragraph])
let size = sizeOfAttributeString(attributedString, maxWidth: maxWidth)
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Yellow is barbackgroundView. Black opacity is BarContentView.
黄色是barbackgroundView。黑色不透明度是 BarContentView。
And I removed BarContentView's backgroundColor.
我删除了 BarContentView 的 backgroundColor。
That's It.
就是这样。
回答by Minster.Zo
this works for me :
这对我有用:
- (CGSize)sizeThatFits:(CGSize)size {
CGSize sizeThatFit = [super sizeThatFits:size];
if ([UIApplication sharedApplication].isStatusBarHidden) {
if (sizeThatFit.height < 64.f) {
sizeThatFit.height = 64.f;
}
}
return sizeThatFit;
}
- (void)setFrame:(CGRect)frame {
if ([UIApplication sharedApplication].isStatusBarHidden) {
frame.size.height = 64;
}
[super setFrame:frame];
}
- (void)layoutSubviews
{
[super layoutSubviews];
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) containsString:@"BarBackground"]) {
CGRect subViewFrame = subview.frame;
subViewFrame.origin.y = 0;
subViewFrame.size.height = 64;
[subview setFrame: subViewFrame];
}
if ([NSStringFromClass([subview class]) containsString:@"BarContentView"]) {
CGRect subViewFrame = subview.frame;
subViewFrame.origin.y = 20;
subViewFrame.size.height = 44;
[subview setFrame: subViewFrame];
}
}
}
回答by CharlieSu
Added: The problem is solved in iOS 11 beta 6 ,so the code below is of no use ^_^
补充:问题在iOS 11 beta 6中解决,所以下面的代码没有用^_^
Original answer:
原答案:
Solved with code below :
用下面的代码解决:
(I always want the navigationBar.height + statusBar.height == 64 whether the hidden of statusBar is true or not)
(我一直想要navigationBar.height + statusBar.height == 64 不管statusBar的隐藏是否为真)
@implementation P1AlwaysBigNavigationBar
- (CGSize)sizeThatFits:(CGSize)size {
CGSize sizeThatFit = [super sizeThatFits:size];
if ([UIApplication sharedApplication].isStatusBarHidden) {
if (sizeThatFit.height < 64.f) {
sizeThatFit.height = 64.f;
}
}
return sizeThatFit;
}
- (void)setFrame:(CGRect)frame {
if ([UIApplication sharedApplication].isStatusBarHidden) {
frame.size.height = 64;
}
[super setFrame:frame];
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (![UIApplication sharedApplication].isStatusBarHidden) {
return;
}
for (UIView *subview in self.subviews) {
NSString* subViewClassName = NSStringFromClass([subview class]);
if ([subViewClassName containsString:@"UIBarBackground"]) {
subview.frame = self.bounds;
}else if ([subViewClassName containsString:@"UINavigationBarContentView"]) {
if (subview.height < 64) {
subview.y = 64 - subview.height;
}else {
subview.y = 0;
}
}
}
}
@end
回答by Peymankh
Simplified with Swift 4.
使用 Swift 4 进行简化。
class CustomNavigationBar : UINavigationBar {
private let hiddenStatusBar: Bool
// MARK: Init
init(hiddenStatusBar: Bool = false) {
self.hiddenStatusBar = hiddenStatusBar
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Overrides
override func layoutSubviews() {
super.layoutSubviews()
if #available(iOS 11.0, *) {
for subview in self.subviews {
let stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarBackground") {
subview.frame = self.bounds
} else if stringFromClass.contains("BarContentView") {
let statusBarHeight = self.hiddenStatusBar ? 0 : UIApplication.shared.statusBarFrame.height
subview.frame.origin.y = statusBarHeight
subview.frame.size.height = self.bounds.height - statusBarHeight
}
}
}
}
}
回答by reggian
Along with overriding -layoutSubviews
and -setFrame:
you should check out the newly added UIViewController's additionalSafereaInsets
property (Apple Documentation) if you do not want the resized navigation bar hiding your content.
除了覆盖-layoutSubviews
,如果您不希望调整大小的导航栏隐藏您的内容,-setFrame:
您应该查看新添加的 UIViewController 的additionalSafereaInsets
属性(Apple 文档)。
回答by strangetimes
Although it's fixed in beta 4, it seems the background image of the nav bar does not scale with the actual view (you can verify this by looking at at in the view-hierarchy viewer). A workaround for now is to override layoutSubviews
in your custom UINavigationBar
and then use this code:
尽管它在 beta 4 中已修复,但导航栏的背景图像似乎并未随实际视图缩放(您可以通过查看视图层次结构查看器来验证这一点)。现在的解决方法是覆盖layoutSubviews
您的自定义UINavigationBar
,然后使用以下代码:
- (void)layoutSubviews
{
[super layoutSubviews];
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) containsString:@"BarBackground"]) {
CGRect subViewFrame = subview.frame;
subViewFrame.origin.y = -20;
subViewFrame.size.height = CUSTOM_FIXED_HEIGHT+20;
[subview setFrame: subViewFrame];
}
}
}
If you notice, the bar background in fact has an offset of -20
to make it appear behind the status bar, so the calculation above adds that in.
如果您注意到,栏背景实际上有一个偏移量,-20
使其出现在状态栏后面,因此上面的计算将其添加进来。
回答by Marco Pappalardo
on Xcode 9 Beta 6 I still have the issue. The Bar always looks 44 pixel height and it is pushed under the status bar.
在 Xcode 9 Beta 6 上我仍然有这个问题。Bar 总是看起来 44 像素高,它被推到状态栏下方。
In order to solve that I made a subclass with @strangetimes code (in Swift)
为了解决这个问题,我用@strangetimes 代码创建了一个子类(在 Swift 中)
class NavigationBar: UINavigationBar {
override func layoutSubviews() {
super.layoutSubviews()
for subview in self.subviews {
var stringFromClass = NSStringFromClass(subview.classForCoder)
print("--------- \(stringFromClass)")
if stringFromClass.contains("BarBackground") {
subview.frame.origin.y = -20
subview.frame.size.height = 64
}
}
}
}
and I place the bar lower than the status bar
我把栏低于状态栏
let newNavigationBar = NavigationBar(frame: CGRect(origin: CGPoint(x: 0,
y: 20),
size: CGSize(width: view.frame.width,
height: 64)
)
)
回答by Jelly
This is what I use. It works for regular content (44.0 px) if you use UISearchBar
as title or other views that modify the size of the bar content, you must update the values accordingly. Use this at your own risk since it might brake at some point.
这就是我使用的。它适用于常规内容(44.0 像素),如果您UISearchBar
用作修改栏内容大小的标题或其他视图,则必须相应地更新值。使用它需要您自担风险,因为它可能会在某些时候刹车。
This is the navbar with 90.0px height hardcoded, working on both iOS 11 and older versions. You might have to add some insets to the UIBarButtonItem
for pre iOS 11 to look the same.
这是具有 90.0px 高度硬编码的导航栏,适用于 iOS 11 和旧版本。您可能需要UIBarButtonItem
为 iOS 11 之前的版本添加一些插图以使其看起来相同。
class NavBar: UINavigationBar {
override init(frame: CGRect) {
super.init(frame: frame)
if #available(iOS 11, *) {
translatesAutoresizingMaskIntoConstraints = false
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: 70.0)
}
override func layoutSubviews() {
super.layoutSubviews()
guard #available(iOS 11, *) else {
return
}
frame = CGRect(x: frame.origin.x, y: 0, width: frame.size.width, height: 90)
if let parent = superview {
parent.layoutIfNeeded()
for view in parent.subviews {
let stringFromClass = NSStringFromClass(view.classForCoder)
if stringFromClass.contains("NavigationTransition") {
view.frame = CGRect(x: view.frame.origin.x, y: frame.size.height - 64, width: view.frame.size.width, height: parent.bounds.size.height - frame.size.height + 4)
}
}
}
for subview in self.subviews {
var stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarBackground") {
subview.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 90)
subview.backgroundColor = .yellow
}
stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarContent") {
subview.frame = CGRect(x: subview.frame.origin.x, y: 40, width: subview.frame.width, height: subview.frame.height)
}
}
}
}
And you add it to a UINavigationController
subclass like this:
然后将其添加到UINavigationController
子类中,如下所示:
class CustomBarNavigationViewController: UINavigationController {
init() {
super.init(navigationBarClass: NavBar.self, toolbarClass: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init(rootViewController: UIViewController) {
super.init(navigationBarClass: NavBar.self, toolbarClass: nil)
self.viewControllers = [rootViewController]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
回答by Lance Samaria
This works well for the regular navigation bar. If your using the LargeTitle this wont work well because the titleView size isn't going to be a fixed height of 44 points. But for the regular view this should be suffice.
这适用于常规导航栏。如果您使用 LargeTitle 这将无法正常工作,因为 titleView 大小不会是 44 点的固定高度。但是对于常规视图,这应该就足够了。
Like @frangulyan apple suggested to add a view beneath the navBar and hide the thin line (shadow image). This is what I came up with below. I added an uiview to the navigationItem's titleView and then added an imageView inside that uiview. I removed the thin line (shadow image). The uiview I added is the same exact color as the navBar. I added a uiLabel inside that view and that's it.
就像@frangulyan 苹果建议在导航栏下方添加一个视图并隐藏细线(阴影图像)。这是我在下面想到的。我向导航项的 titleView 添加了一个 uiview,然后在该 uiview 中添加了一个 imageView。我删除了细线(阴影图像)。我添加的 uiview 与 navBar 的颜色完全相同。我在该视图中添加了一个 uiLabel,仅此而已。
Here's the 3d image. The extended view is behind the usernameLabel underneath the navBar. Its gray and has a thin line underneath of it. Just anchor your collectionView or whatever underneath of the thin separatorLine.
这是 3d 图像。扩展视图位于导航栏下方的 usernameLabel 后面。它是灰色的,下面有一条细线。只需锚定您的 collectionView 或细分离线下方的任何内容。
The 9 steps are explained above each line of code:
每行代码上面解释了9个步骤:
class ExtendedNavController: UIViewController {
fileprivate let extendedView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
return view
}()
fileprivate let separatorLine: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .gray
return view
}()
fileprivate let usernameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 14)
label.text = "username goes here"
label.textAlignment = .center
label.lineBreakMode = .byTruncatingTail
label.numberOfLines = 1
return label
}()
fileprivate let myTitleView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view
}()
fileprivate let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.backgroundColor = .darkGray
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// 1. the navBar's titleView has a height of 44, set myTitleView height and width both to 44
myTitleView.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
// 2. set myTitleView to the nav bar's titleView
navigationItem.titleView = myTitleView
// 3. get rid of the thin line (shadow Image) underneath the navigationBar
navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
navigationController?.navigationBar.layoutIfNeeded()
// 4. set the navigationBar's tint color to the color you want
navigationController?.navigationBar.barTintColor = UIColor(red: 249.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1.0)
// 5. set extendedView's background color to the same exact color as the navBar's background color
extendedView.backgroundColor = UIColor(red: 249.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1.0)
// 6. set your imageView to get pinned inside the titleView
setProfileImageViewAnchorsInsideMyTitleView()
// 7. set the extendedView's anchors directly underneath the navigation bar
setExtendedViewAndSeparatorLineAnchors()
// 8. set the usernameLabel's anchors inside the extendedView
setNameLabelAnchorsInsideTheExtendedView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
// 9. **Optional** If you want the shadow image to show on other view controllers when popping or pushing
navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
navigationController?.navigationBar.setValue(false, forKey: "hidesShadow")
navigationController?.navigationBar.layoutIfNeeded()
}
func setExtendedViewAndSeparatorLineAnchors() {
view.addSubview(extendedView)
view.addSubview(separatorLine)
extendedView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
extendedView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
extendedView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
extendedView.heightAnchor.constraint(equalToConstant: 29.5).isActive = true
separatorLine.topAnchor.constraint(equalTo: extendedView.bottomAnchor).isActive = true
separatorLine.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
separatorLine.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
separatorLine.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
}
func setProfileImageViewAnchorsInsideMyTitleView() {
myTitleView.addSubview(profileImageView)
profileImageView.topAnchor.constraint(equalTo: myTitleView.topAnchor).isActive = true
profileImageView.centerXAnchor.constraint(equalTo: myTitleView.centerXAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true
// round the profileImageView
profileImageView.layoutIfNeeded()
profileImageView.layer.cornerRadius = profileImageView.frame.width / 2
}
func setNameLabelAnchorsInsideTheExtendedView() {
extendedView.addSubview(usernameLabel)
usernameLabel.topAnchor.constraint(equalTo: extendedView.topAnchor).isActive = true
usernameLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
usernameLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
}