iOS 11 - 无法更改导航栏高度 [英] iOS 11 - Unable to change Navigation Bar height

查看:1090
本文介绍了iOS 11 - 无法更改导航栏高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,我刚刚升级到Xcode 9 / Swift 4,并且还将我的iPhone升级到了iOS 11.
当我安装iOS 11时,应用程序已经安装好,直到我从Xcode中。现在我陷入了默认的NavBar高度。



我用来更改高度的代码不再有效:

  class CustomNavControllerVC:UINavigationController 
{
let navBarHeight:CGFloat = 64.0
let navbarBackButtonColor = UIColor(红色:247/255,绿色:179 / 255,蓝色:20/255,alpha:1)

覆盖func viewDidLoad()
{
super.viewDidLoad()

print( CustomNavControllerVC> viewDidLoad)
}

覆盖func viewDidLayoutSubviews()
{
print(CustomNavControllerVC> viewDidLayoutSubviews)

super.viewDidLayoutSubviews()

navigationBar.frame.size.height = navBarHeight
navigationBar.tintColor = navbarBackButtonColor
}

覆盖func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
//处理任何资源可以重新创建。
}
}


//在我的VC中

覆盖func viewDidLoad()
{
customizeNavBar ()
}


func customizeNavBar()
{
让navbarBackItem = UIBarButtonItem()
navbarBackItem.title =Înapoi
navigationItem.backBarButtonItem = navbarBackItem

让navbarImageView = UIImageView(frame:CGRect(x:0,y:0,width:55,height:20))
navbarImageView.contentMode = .scaleToFill

让navbarLogo = UIImage(名称:NavBarLogo.png)
navbarImageView.image = navbarLogo

navigationItem.titleView = navbarImageView
}

到目前为止,我在这个问题上唯一能找到的是:







设置自定义NavigationBar类







添加TestView +设置SafeArea



ViewController.swift

  import UIKit 

class ViewController:UIViewController {

var navbar:UINavigationBar!

@IBOutlet weak var testView:UIView!

覆盖func viewDidLoad(){
super.viewDidLoad()

//更新NavigationBar的框架
self.navigationController?.navigationBar.sizeToFit()
print(NavigationBar Frame:\(String(describe:self.navigationController!.navigationBar.frame)))

}

//隐藏状态栏
覆盖var prefersStatusBarHidden:Bool {

返回true
}

覆盖func viewDidAppear(_ animated:Bool){

super.viewDidAppear(false)

//重要!
if #available(iOS 11.0,*){

//默认NavigationBar高度为44.自定义NavigationBar高度为66.所以我们应该将additionalSafeAreaInsets设置为66-44 = 22
self.additionalSafeAreaInsets.top = 22

}

}

覆盖func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处置可以重新创建的任何资源。
}


}

SecondViewController.swift

  import UIKit 

class SecondViewController:UIViewController {

override func viewDidLoad (){
super.viewDidLoad()

//加载视图后进行任何其他设置。


//创建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)


}
覆盖var prefersStatusBarHidden:Bool {

返回true
}
@ objc func back(_ sender:UITabBarItem){

self.navigationController?.popViewController(animated:true)

}


// Helper函数:获取字符串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
}


//帮助函数:将字符串转换为UIImage
func imageFromText(_ text:NSString,font:UIFont,maxWidth:CGFloat,color:UIColor) - > UIImage
{
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.byWordWrapping
paragraph.alignment = .center //这可能也是一个输入参数,但是我猜测在大多数用例中我们想要居中对齐

let attributionString = 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()
返回图片!
}




覆盖func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处置任何资源可以重新创建。
}



}




黄色是barbackgroundView。黑色不透明度是BarContentView。



我删除了BarContentView的backgroundColor。





就是这样。


I am working on an application and I just upgraded to Xcode 9 / Swift 4 and also upgraded my iPhone to iOS 11. The application was installed when I installed iOS 11 and all seemed OK until I run it from Xcode. Now I am stuck with the default NavBar height.

The code I was using to change the height is no longer working:

class CustomNavControllerVC: UINavigationController
{
    let navBarHeight : CGFloat = 64.0
    let navbarBackButtonColor = UIColor(red: 247/255, green: 179/255, blue: 20/255, alpha: 1)

    override func viewDidLoad()
    {
        super.viewDidLoad()

        print("CustomNavControllerVC > viewDidLoad")
    }

    override func viewDidLayoutSubviews()
    {
        print("CustomNavControllerVC > viewDidLayoutSubviews")

        super.viewDidLayoutSubviews()

        navigationBar.frame.size.height = navBarHeight
        navigationBar.tintColor = navbarBackButtonColor
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


// In my VCs

override func viewDidLoad()
{
    customizeNavBar()
}


func customizeNavBar()
{
    let navbarBackItem = UIBarButtonItem()
    navbarBackItem.title = "Înapoi"
    navigationItem.backBarButtonItem = navbarBackItem

    let navbarImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 55, height: 20))
    navbarImageView.contentMode = .scaleToFill

    let navbarLogo = UIImage(named: "NavBarLogo.png")
    navbarImageView.image = navbarLogo

    navigationItem.titleView = navbarImageView
}

So far the only thing I could find on this issue is this:

iOS 11 navigation bar height customizing

iOS11 customize navigation bar height

How to correctly set UINavigationBar height in iOS 11

But the info provided does not help, unfortunately.

Any ideas / suggestions?

解决方案

Updated 2017.10.6

I had the same problem. Below is my solution. I assume that height size is 66.

My solution is working fine iOS 10, 11.

Please choose my answer if it helps you.

Create NavgationBar.swift

import UIKit

class NavigationBar: UINavigationBar {

    //set NavigationBar's height
    var customHeight : CGFloat = 66

    override func sizeThatFits(_ size: CGSize) -> CGSize {

        return CGSize(width: UIScreen.main.bounds.width, height: customHeight)

    }

    override func layoutSubviews() {
        super.layoutSubviews()

        frame = CGRect(x: frame.origin.x, y:  0, width: frame.size.width, height: customHeight)

        // title position (statusbar height / 2)
        setTitleVerticalPositionAdjustment(-10, for: UIBarMetrics.default)

        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: customHeight)
                subview.backgroundColor = .yellow

            }

            stringFromClass = NSStringFromClass(subview.classForCoder)
            if stringFromClass.contains("BarContent") {

                subview.frame = CGRect(x: subview.frame.origin.x, y: 20, width: subview.frame.width, height: customHeight - 20)

                subview.backgroundColor = UIColor(red: 20/255, green: 20/255, blue: 20/255, alpha: 0.4)

            }
        }
    }


}

Set Storyboard

Set Custom NavigationBar class

Add TestView + Set SafeArea

ViewController.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

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.

And I removed BarContentView's backgroundColor.

That's It.

这篇关于iOS 11 - 无法更改导航栏高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆