使用插入图像自定义 UINavigationBar

Customize UINavigationBar with inset image

我有这个导航栏,我正在尝试实现它,它看起来像这样: 我知道我可以将图像直接放在导航栏中或作为其下方的 header 图像,但我不知道如何插入它以便它既包含在主容器视图中又包含在导航栏中还有。

任何想法都会有所帮助!

我想使用两张图片可以实现:

  1. background: 会匹配导航栏框架

  1. icon:假设图像 50x50 在 x 轴和 y 轴上以背景为中心,其高度偏移 / 2.0

那么你可以尝试使用自动布局约束这样做:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let navbar = self.navigationController?.navigationBar else {return} // be sure to have defined a navigation controller
        navbar.clipsToBounds = false // so the icon will be visible outside the nav bar

        let niceBkg = UIImageView(image: UIImage(named: "bkg"))
        navbar.addSubview(niceBkg)
        niceBkg.translatesAutoresizingMaskIntoConstraints = false
        niceBkg.leftAnchor.constraint(equalTo: navbar.leftAnchor).isActive = true
        niceBkg.rightAnchor.constraint(equalTo: navbar.rightAnchor).isActive = true
        niceBkg.topAnchor.constraint(equalTo: self.navigationController!.view.topAnchor).isActive = true
        niceBkg.bottomAnchor.constraint(equalTo: navbar.bottomAnchor).isActive = true

        let niceIcon = UIImageView(image: UIImage(named: "icon"))
        niceBkg.addSubview(niceIcon)
        niceIcon.translatesAutoresizingMaskIntoConstraints = false
        niceIcon.widthAnchor.constraint(equalToConstant: 50).isActive = true
        niceIcon.heightAnchor.constraint(equalToConstant: 50).isActive = true
        niceIcon.centerXAnchor.constraint(lessThanOrEqualTo: niceBkg.centerXAnchor).isActive = true
        niceIcon.bottomAnchor.constraint(greaterThanOrEqualTo: niceBkg.bottomAnchor, constant: 25).isActive = true
    }
}

在 iPhoneX 上结果是:


关于您的场景,您可能只需要图​​标和具有适当背景颜色的导航栏。但是我添加了两个自动布局配置,因为可能对其他人有用,特别是如果导航栏的背景非常复杂,有边框、装饰等。