如何在 iOS 中的导航中制作带有徽标和文本的自定义导航栏?

How to make a custom navigation bar with logo and a text in the navigation in iOS?

因为我来自混合应用程序背景,所以我想在 iOS 中实现 UI,其中包含徽标和文本。下面是一个蓝色条带,其中包含“返回”和“注册”作为标题。单击返回时,它会转到上一个控制器。我怎样才能做到这一点 UI?我尝试使用下面的给定代码:但我不确定如何继续。

func addNavBarImage() {
        let navController = navigationController!
        let image = UIImage(named: "logo-signIn6.png") //Your logo url here
        let imageView = UIImageView(image: image)
        let bannerWidth = navController.navigationBar.frame.size.width
        let bannerHeight = navController.navigationBar.frame.size.height
        let bannerX = bannerWidth / 2 - (image?.size.width)! / 2
        let bannerY = bannerHeight / 2 - (image?.size.height)! / 2
        imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
        imageView.contentMode = .scaleAspectFit
        navigationItem.titleView = imageView
    }

下面是我想要实现的 UI 的图像。

您可以将自定义视图分配给 navigationItem.titleView。这是一个非常简单的代码,用于将图像和文本分配给 titleView。我鼓励您创建一个单独的视图 class,您可以在其中定义自定义视图,然后将其分配给 titleView

override func viewDidLoad() {
    super.viewDidLoad()

    let imageView = UIImageView()
    imageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 30).isActive = true

    let titleLabel = UILabel()
    titleLabel.text = "Your title"

    let stackView = UIStackView(arrangedSubviews: [imageView, titleLabel])
    stackView.spacing = 5
    stackView.alignment = .center

    // This will assing your custom view to navigation title. 
    navigationItem.titleView = stackView
}