1

我想使用带有文本的自定义图标作为preferLargeTitles启用的导航栏的标题。自定义标题首先需要很大并居中,然后在滚动时调整大小。它应该是这样的:带有包含图标和文本的标题的大型导航栏

在此处输入图像描述

我曾尝试将图像与图标和文本一起使用,这样我就可以创建一个imageView并将 titleView 设置为此,但是这会导致一个小的居中视图覆盖大导航栏。

在此处输入图像描述

我该怎么做呢?我希望自定义标题的行为与默认的大导航栏一样,并在向上滚动时调整图像大小和居中。谢谢!

4

1 回答 1

1

尝试这个

    // Create a navView to add to the navigation bar
    let navView = UIView()

    // Create the label
    let label = UILabel()
    label.text = "Assignment"
    label.font = UIFont.systemFont(ofSize: 30.0, weight: .bold)
    label.sizeToFit()
    label.center = navView.center
    label.textAlignment = NSTextAlignment.center

    // Create the image view
    let image = UIImageView()
    image.image = UIImage(named: "logo.png")
    let imageAspect = image.image!.size.width/image.image!.size.height
    image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect - 5, y: label.frame.origin.y, width: label.frame.size.height*imageAspect, height: label.frame.size.height)
    image.contentMode = UIViewContentMode.scaleAspectFit

    // Add both the label and image view to the navView
    navView.addSubview(label)
    navView.addSubview(image)

    // Set the navigation bar's navigation item's titleView to the navView
    self.navigationItem.titleView = navView
    self.navigationController?.navigationBar.prefersLargeTitles = true

输出:

在此处输入图像描述

于 2018-06-05T07:35:46.390 回答