在Swift 4中的UINavigationBar中将图像设置为标题

时间:2018-09-13 04:44:19

标签: ios swift uinavigationbar swift4 ios11

对于导航栏,我具有以下代码,该代码为标题设置了单词Title,但希望改为我的徽标。

\.?

如果我想要方形徽标,@ 1x,@ 2x和@ 3x的像素大小也应为多少?徽标也是我的应用程序图标。

2 个答案:

答案 0 :(得分:0)

不能完全确定这是否是您要实现的目标,但是已经有一些建议。

这是一个受欢迎的:

let logo = UIImage(named: "logo") // Or logo.png if you haven't added it to assets
let imageView = UIImageView(frame: CGRect(x:0, y:0, width:50.0, height:50.0))
imageView.image = logo
imageView.contentMode = .scaleAspectFit
self.navigationItem.titleView = imageView

或者可以使用这种方法:

func addNavBarImage() {

    let navController = navigationController!

    let image = UIImage(named: "logo.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
}

question的答案。

答案 1 :(得分:0)

尝试这个

// top-logo = your image name 
if let logo = UIImage(named: "top-logo"){
    let imageView = UIImageView(image:logo)
    self.navigationItem.titleView = imageView
}

输出:

enter image description here