带有UIImage标题的导航栏


70

我想通过使用徽标图像(而不是纯文本)作为导航栏的标题来自定义应用程序的外观。当我使用此代码

let logo = UIImage(named: "logo.png")
self.navigationItem.titleView = logo;

我收到错误“ UIImage无法转换为UIView”。如何正确执行此操作?

Answers:


185

放在里面 UIImageView

let logo = UIImage(named: "logo.png")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView

您将其放在类声明中的什么位置?
azochz 2014年

@JackWu如果将其添加到UINavigationController.viewDidLoad(为导航控制器实现的类),则不起作用,但如果将其添加到,则它可以工作ViewController。但我想将此代码分开(因此在扩展UINavigationController的类中)。可能吗?
Patriks

@ Ronaldoh1这与您的回答完全相同,所以我不知道您怎么能说“这不再起作用了”
Jack

3
这可行,但是您必须viewDidLoad在推送到导航控制器的视图控制器中使用,而不是在导航控制器本身中使用。
Martin Marconcini

@MartínMarconcini感谢您澄清这一点。那就是问题所在。
dcgoss

57

我用这个 它适用于iOS 8

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let image = UIImage(named: "YOURIMAGE")
    navigationItem.titleView = UIImageView(image: image)
}

这是一个示例,您如何使用CGRect做到这一点。

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 38, height: 38))
    imageView.contentMode = .ScaleAspectFit
    let image = UIImage(named: "YOURIMAGE")
    imageView.image = image
    navigationItem.titleView = imageView
}

希望这会有所帮助。


您将其放在导航栏子类中的什么位置?
侯赛因,2015年

@侯赛因我不记得了,已经有一段时间了,没有这个项目。抱歉。
Fernando S. Kroes

2
这样效果更好,并且图像按我的意愿缩放。这应该是公认的答案。
穆尼卜

34

对于Swift 4,您可以调整imageView的大小

 let logoContainer = UIView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))

 let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
 imageView.contentMode = .scaleAspectFit
 let image = UIImage(named: "your_image")
 imageView.image = image
 logoContainer.addSubview(imageView)
 navigationItem.titleView = logoContainer

非常感谢
Mohammad Razipour

13

我在上面尝试了@Jack的答案,徽标确实出现了,但是图像占据了整个导航栏。我想要它适合。

Swift 4,Xcode 9.2

1.将值分配给导航控制器UIImage。通过划分帧和图像尺寸来调整尺寸。

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
    }
  1. 在下面添加功能 viewDidLoad()

        addNavBarImage() 
    

注意图像资产。上传之前,我调整了徽标的余量,而不是在边缘进行裁切。

最后结果:

在此处输入图片说明


大。非常感谢你的队友!
标记

@Mark Just获得了另一个死灵法师徽章。希望它能解决您的酒吧形象伙伴!
Cons Bulaquena

调整大小对我不起作用,但是我通过增加左右条项目宽度的大小来修复它。
编码器ACJHP

9

您可以使用自定义UINavigationItem,因此只需在Main.storyboard上将“ Navigation Item”更改为YourCustomClass。

在Swift 3中

class FixedImageNavigationItem: UINavigationItem {

private let fixedImage : UIImage = UIImage(named: "your-header-logo.png")!
private let imageView : UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 37.5))

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    imageView.contentMode = .scaleAspectFit
    imageView.image = fixedImage
    self.titleView = imageView

}

}

5

这在2015年9月对我有用-希望这对在那里的人有所帮助。

// 1
    var nav = self.navigationController?.navigationBar
    // 2 set the style 
    nav?.barStyle = UIBarStyle.Black
    nav?.tintColor = UIColor.yellowColor()
    // 3
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
    imageView.contentMode = .ScaleAspectFit
    // 4
    let image = UIImage(named: "logo.png")
    imageView.image = image
    // 5
    navigationItem.titleView = imageView

1
如果此解决方案不起作用,请尝试在UIViewController类中创建对导航栏的引用。@IBOutlet弱var navBar:UINavigationBar!然后而不是 navigationItem.titleView = imageViewself.navBar.topItem?.titleView = imageView 它在这里解释:
knopch1425


5

这是Swift 4.2的便捷功能,显示带有标题文本的图像:-

在此处输入图片说明

override func viewDidLoad() {

    super.viewDidLoad()

    //Sets the navigation title with text and image
    self.navigationItem.titleView = navTitleWithImageAndText(titleText: "Dean Stanley", imageName: "online")
}

func navTitleWithImageAndText(titleText: String, imageName: String) -> UIView {

    // Creates a new UIView
    let titleView = UIView()

    // Creates a new text label
    let label = UILabel()
    label.text = titleText
    label.sizeToFit()
    label.center = titleView.center
    label.textAlignment = NSTextAlignment.center

    // Creates the image view
    let image = UIImageView()
    image.image = UIImage(named: imageName)

    // Maintains the image's aspect ratio:
    let imageAspect = image.image!.size.width / image.image!.size.height

    // Sets the image frame so that it's immediately before the text:
    let imageX = label.frame.origin.x - label.frame.size.height * imageAspect
    let imageY = label.frame.origin.y

    let imageWidth = label.frame.size.height * imageAspect
    let imageHeight = label.frame.size.height

    image.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)

    image.contentMode = UIView.ContentMode.scaleAspectFit

    // Adds both the label and image view to the titleView
    titleView.addSubview(label)
    titleView.addSubview(image)

    // Sets the titleView frame to fit within the UINavigation Title
    titleView.sizeToFit()

    return titleView

}

这很好。一个问题:我们如何确保图像始终是圆形的?角半径应如何设置?@Gagandeep
Vandal

3

Swift 5.1,Xcode 11

有时,如果您的图像分辨率较高,则imageView会偏离中心,我建议您使用此方法

  lazy var navigationTitleImageView = UIImageView()

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.setNavigationBar()
    
    self.navigationTitleImageView.image = logo
    self.navigationTitleImageView.contentMode = .scaleAspectFit
    
    self.navigationTitleImageView.translatesAutoresizingMaskIntoConstraints = false
    
    if let navC = self.navigationController{
        navC.navigationBar.addSubview(self.navigationTitleImageView)
        self.navigationTitleImageView.centerXAnchor.constraint(equalTo: navC.navigationBar.centerXAnchor).isActive = true
        self.navigationTitleImageView.centerYAnchor.constraint(equalTo: navC.navigationBar.centerYAnchor, constant: 0).isActive = true
        self.navigationTitleImageView.widthAnchor.constraint(equalTo: navC.navigationBar.widthAnchor, multiplier: 0.2).isActive = true
        self.navigationTitleImageView.heightAnchor.constraint(equalTo: navC.navigationBar.widthAnchor, multiplier: 0.088).isActive = true
    }
}

和viewWillDisappear()

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.navigationTitleImageView.removeFromSuperview()
}

否则只是缩小图像尺寸


2

如果您希望使用自动布局,并希望在导航栏中添加永久的固定图像,并且该图像不会与每个屏幕一起显示,则此解决方案效果很好:

class CustomTitleNavigationController: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    let logo = UIImage(named: "MyHeaderImage")

    let imageView = UIImageView(image:logo)
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    navigationBar.addSubview(imageView)

    navigationBar.addConstraint (navigationBar.leftAnchor.constraint(equalTo: imageView.leftAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.rightAnchor.constraint(equalTo: imageView.rightAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.topAnchor.constraint(equalTo: imageView.topAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.bottomAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 0))
}

2

我为iOS 10和iOS 11编写了此代码,它对我有用:

extension UINavigationBar {
    func setupNavigationBar() {
        let titleImageWidth = frame.size.width * 0.32
        let titleImageHeight = frame.size.height * 0.64
        var navigationBarIconimageView = UIImageView()
        if #available(iOS 11.0, *) {
            navigationBarIconimageView.widthAnchor.constraint(equalToConstant: titleImageWidth).isActive = true
            navigationBarIconimageView.heightAnchor.constraint(equalToConstant: titleImageHeight).isActive = true
        } else {
            navigationBarIconimageView = UIImageView(frame: CGRect(x: 0, y: 0, width: titleImageWidth, height: titleImageHeight))
        }
        navigationBarIconimageView.contentMode = .scaleAspectFit
        navigationBarIconimageView.image = UIImage(named: "image")
        topItem?.titleView = navigationBarIconimageView
    }
}

1

让我们尝试结帐

let image = UIImage(named: "Navbar_bg.png")
navigationItem.titleView = UIImageView(image: image)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .ScaleAspectFit

2
尽管此代码段可以解决问题,但提供说明确实有助于提高您的帖子质量。请记住,您将来会为读者回答这个问题,而这些人可能不知道您提出代码建议的原因。
vaultah '16

1
    let imageView = UIImageView(frame: (CGRect(x: 0, y: 0, width: 40, height: 
    40)))
    imageView.contentMode = .scaleAspectFit
    let image = UIImage (named: "logo") // logo is your NPG asset 
    imageView.image = image
    self.navigationItem.titleView = imageView

3
请详细说明您的代码的作用。仅代码答案在StackOverflow中被认为是劣质的。
quinz

1

在Swift 4为我工作(方形图片40x40)

let imageView = UIImageView()
imageView.frame.size.width = 40
imageView.frame.size.height = 40
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "YOUR_IMAGE_NAME")
imageView.image = image
navigationItem.titleView = imageView

如果您需要其他措施,请尝试

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 100.5)))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "YOUR_IMAGE_NAME")
imageView.image = image
navigationItem.titleView = imageView

我希望它能为您服务。这个对我有用。


1

可以像这样以编程方式完成。

private var imageView: UIView {

    let bannerWidth = navigationBar.frame.size.width * 0.5 // 0.5 its multiplier to get correct image width
    let bannerHeight = navigationBar.frame.size.height

    let view = UIView()
    view.backgroundColor = .clear
    view.frame = CGRect(x: 0, y: 0, width: bannerWidth, height: bannerHeight)

    let image = UIImage(named: "your_image_name")
    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    imageView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)

    view.addSubview(imageView)

    return view
}

只需更改titleView

navigationItem.titleView = imageView

0

Objective-C版本:

//create the space for the image
UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 256, 144)];
//bind the image with the ImageView allocated
myImage.image = [UIImage imageNamed:@"logo.png"];
//add image into imageview
_myNavigationItem.titleView = myImage;

以防万一有人(像我一样)到达这里在Objective-C中寻找答案。


0

这对我有用...尝试

let image : UIImage = UIImage(named: "LogoName")
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
imageView.contentMode = .scaleAspectFit
imageView.image = image
navigationItem.titleView = imageView

0

为了获得具有适当大小且在中心的图像视图,您应该使用以下方法:

let width = 120 // choose the image width
let height = 20 // choose the image height
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)) //44 is the standard size of the top bar
let imageView = UIImageView(frame: CGRect(x: (view.bounds.width - width)/2, y: (44 - height)/2, width: width, height: height))
imageView.contentMode = .scaleAspectFit //choose other if it makes sense
imageView.image = UIImage(named: "your_image_name")
titleView.addSubview(imageView)
navigationItem.titleView = titleView
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.