iOS-在导航栏标题中添加图像和文本 [英] iOS - add image and text in title of Navigation bar

查看:632
本文介绍了iOS-在导航栏标题中添加图像和文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个导航栏,类似于所附图像中的导航栏.

I would like to create a nav bar similar to what's in the image that's attached.

导航栏的标题将是图像和文本的组合.

The title of the nav bar will be a combination of an image and text.

  1. 是否应按照最佳做法进行操作?

  1. Should this be done per any best practice?

该怎么办?

推荐答案

正如此答案所示,最简单的解决方案是将文本添加到图像并将该图像添加到导航栏,如下所示:

As this answer shows, the easiest solution is to add the text to your image and add that image to the navigation bar like so:

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

但是,如果您必须分别添加文本和图像(例如,在本地化的情况下),则可以通过将导航栏的标题视图添加到UIView并将其设置为例如,navigationItem对该UIView的标题视图(假设导航栏是导航控制器的一部分):

But if you have to add text and an image separately (for example, in the case of localization), you can set your navigation bar's title view to contain both image and text by adding them to a UIView and setting the navigationItem's title view to that UIView, for example (assuming the navigation bar is part of a navigation controller):

// Only execute the code if there's a navigation controller 
if self.navigationController == nil {
    return
}

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

// Create the label
let label = UILabel()
label.text = "Text"
label.sizeToFit()
label.center = navView.center
label.textAlignment = NSTextAlignment.Center

// Create the image view
let image = UIImageView()
image.image = UIImage(named: "Image.png")
// To maintain the image's aspect ratio:
let imageAspect = image.image!.size.width/image.image!.size.height
// Setting the image frame so that it's immediately before the text:
image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect, 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

// Set the navView's frame to fit within the titleView
navView.sizeToFit()

这篇关于iOS-在导航栏标题中添加图像和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆