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

标签 swift navigationbar

我想创建一个类似于所附图片中的导航栏。

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

  1. 是否应根据任何最佳实践来完成此操作?

  2. 如何做到?

Screen shot of mockup of nav bar with image and text

最佳答案

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

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

但如果您必须分别添加文本和图像(例如,在本地化的情况下),您可以通过将导航栏的标题 View 添加到 UIView 来将它们设置为同时包含图像和文本。并设置 navigationItem UIView 的标题 View ,例如(假设导航栏是导航 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()

关于swift - iOS - 在导航栏的标题中添加图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38548397/

相关文章:

ios - 当传递到自定义迁移策略中的模型迁移函数时,核心数据实体中的 Int16 支持的枚举属性似乎具有不正确的值

ios - 如何检测 UIView 大小何时在 swift ios xcode 中更改?

android - NavigationBar 和 StatusBar 在某些设备上不完全透明

android - 如何在模拟器中显示系统导航栏

ios - Swift 1.2 - prepareForSegue 针对 View Controller 嵌入式导航 Controller

xcode - 在 iOS 上开发 Microsoft Band

css - 带有包装问题的导航栏

navigationbar - 导航栏 - React Native

php - 如何在不刷新导航栏的情况下加载内容

ios - 在 CoreData [Swift] 中存储 NSArray 的问题