You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift4 iOS导航栏居中标题左侧添加图片实现问题

解决Swift 4中导航栏标题左侧加图片且居中显示的问题

嘿,我来帮你搞定这个导航栏标题的问题!你遇到的情况是因为富文本的拼接顺序搞反啦——你之前应该是先加了文字,再追加图片,所以图片才跑到右边去了。只要调整一下拼接顺序,再配合自定义标题视图,就能完美实现标题居中+左侧带图片的效果。

下面是完整的实现步骤和代码:

步骤1:处理图片尺寸

首先把你要的图片调整到合适大小,避免显示过大或过小:

let image = UIImage(named: "user2")!
let newSize = CGSize(width: 30, height: 30)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.draw(in: CGRect(origin: .zero, size: newSize))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

步骤2:创建图片和文字的富文本

接下来分别把图片和标题文字转换成属性字符串,注意图片要放在文字前面:

// 处理图片的属性字符串,调整垂直对齐让它和文字居中
let imageAttachment = NSTextAttachment()
imageAttachment.image = resizedImage
imageAttachment.bounds = CGRect(x: 0, y: -4, width: newSize.width, height: newSize.height)
let imageAttributedString = NSAttributedString(attachment: imageAttachment)

// 处理标题文字的属性字符串,加个空格和图片隔开
let titleText = "你的应用标题"
let textAttributes: [NSAttributedString.Key: Any] = [
    .font: UIFont.systemFont(ofSize: 17, weight: .medium),
    .foregroundColor: UIColor.black
]
let textAttributedString = NSAttributedString(string: " " + titleText, attributes: textAttributes)

步骤3:拼接富文本并设置为导航栏标题

把图片和文字的富文本按图片在前、文字在后的顺序拼接,然后用自定义UILabel作为导航栏的titleView,确保标题居中:

let combinedAttributedString = NSMutableAttributedString()
combinedAttributedString.append(imageAttributedString)
combinedAttributedString.append(textAttributedString)

let titleLabel = UILabel()
titleLabel.attributedText = combinedAttributedString
titleLabel.sizeToFit()
navigationItem.titleView = titleLabel

为什么之前的方法不行?

你之前两次追加字符串的顺序应该是先加了文字,再追加图片,这就导致图片被放在了文字的右侧。只要把拼接顺序反过来,先加图片再加文字,就能让图片显示在标题左侧啦。另外用自定义UILabel作为titleView,能确保整个标题区域在导航栏中居中显示,比直接设置titleAttributedString更可控。

内容的提问来源于stack exchange,提问作者Android teem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:43:11