加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – iOS – 在导航栏的标题中添加图像和文本

发布时间:2020-12-14 04:53:52 所属栏目:百科 来源:网络整理
导读:我想创建一个类似于附加图像中的导航栏. 导航栏的标题将是图像和文本的组合. 这应该按照最佳做法进行吗? 怎么做? 解决方法 作为 this answer shows,最简单的解决方案是将文本添加到图像并将该图像添加到导航栏,如下所示: var image = UIImage(named: "log
我想创建一个类似于附加图像中的导航栏.

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

>这应该按照最佳做法进行吗?
>怎么做?

解决方法

作为 this answer shows,最简单的解决方案是将文本添加到图像并将该图像添加到导航栏,如下所示:

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

但是,如果必须单独添加文本和图像(例如,在本地化的情况下),您可以将导航栏的标题视图设置为包含图像和文本,方法是将它们添加到UIView并将navigationItem的标题视图设置为例如UIView(假设导航栏是导航控制器的一部分):

// 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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读