无法更改 iOS 11 中的导航栏项目高度

Cannot change navigation bar item height in iOS 11

自定义导航栏高度大于默认值(44pt)后,我想更改右侧导航栏项目按钮的高度,但限制在44pt。我怎样才能让它长得更高?我知道在 iOS 11 中,按钮现在在 UIBarButtonStackView 中,似乎我们无法更改堆栈视图框架?

我使用这段代码来改变按钮的宽度和高度:

button.widthAnchor.constraint(equalToConstant: 40).isActive = true
button.heightAnchor.constraint(equalToConstant: 60).isActive = true
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(image, for: .normal)

let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton

谢谢!

您可以使用此代码更改导航栏按钮项的宽度 -

override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            var frame: CGRect? = navigationItem.leftBarButtonItem?.customView?.frame
            frame?.size.width = 5  // change the width of your item bar button
            self.navigationItem.leftBarButtonItem?.customView?.frame = frame!
        }
        override var prefersStatusBarHidden : Bool {
            return true
        }

或从故事板 -

确保您的 Assets.xcassets 图片设置为 Render As - Original Image Just like -

使用 UInavigationcontroller class 和 NavigationBar class 的 subclass 可以实现这一点。 我正在分享一些代码片段:

class ARVNavigationController { 
 init(rootViewController: UIViewController) {
 super.init(navigationBarClass: AVNavigationBar.self, toolbarClass: nil)

viewControllers = [rootViewController] }}



class AVNavigationBar { 

 let AVNavigationBarHeight: CGFloat = 80.0


 init?(coder aDecoder: NSCoder) {
 super.init(coder: aDecoder)
 initialize()
}



init(frame: CGRect) {
super.init(frame: frame ?? CGRect.zero)
initialize()
}

func initialize() {
   transform = CGAffineTransform(translationX: 0, y: +AVNavigationBarHeight)
}

func layoutSubviews() {
   super.layoutSubviews()
   let classNamesToReposition = ["_UINavigationBarBackground", "UINavigationItemView", "UINavigationButton"]
   for view: UIView? in subviews() {
       if classNamesToReposition.contains(NSStringFromClass(view.self)) {
         let bounds: CGRect = self.bounds()
         let frame: CGRect? = view?.frame
         frame?.origin.y = bounds.origin.y + CGFloat(AVNavigationBarHeight)
         frame?.size.height = bounds.size.height - 20.0
         view?.frame = frame ?? CGRect.zero
       }
   }
}

 func position(for bar: UIBarPositioning) -> UIBarPosition {
    return .topAttached
 }

}