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

iOS如何在UINavigationBar标题处同时显示UIImage和UILabel

问题原因

当你给UINavigationItem显式设置了自定义的titleView属性后,系统自带的标题文本控件会被完全替换,此时单独设置navigationItem.title不会生效,需要自行将图片和文本控件组合到同一个容器视图中,再赋值给titleView。

原有代码中设置的titleTextAttributes是作用于系统默认标题控件的,使用自定义titleView后该配置不再生效,直接给自定义文本控件设置样式即可,相关旧代码可以删除。

修改实现代码
// 1. 构建图片控件
let imageView = UIImageView(image: UIImage(systemName: "flame"))
imageView.tintColor = R.color.fire()
imageView.contentMode = .scaleAspectFit

// 2. 构建标题文本控件
let titleLabel = UILabel()
titleLabel.text = "표시한 제품"
titleLabel.textColor = R.color.myPageMenu
// 字号字重可自行调整,此处和系统默认导航栏标题样式保持一致
titleLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)

// 3. 用水平堆栈视图作为容器组合图文
let titleStackView = UIStackView(arrangedSubviews: [imageView, titleLabel])
titleStackView.axis = .horizontal
titleStackView.spacing = 6 // 图文间距可按需调整
titleStackView.alignment = .center

// 4. 添加固定约束避免布局错乱
titleStackView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: 18).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 18).isActive = true

// 5. 赋值给导航栏titleView
self.navigationItem.titleView = titleStackView
可选调整方案
  • 需要调换图文顺序时,直接修改UIStackView初始化时arrangedSubviews的元素顺序即可
  • 可修改titleStackView.spacing的数值调整图文间距
  • 可自定义titleLabel的字号、字重、颜色等属性匹配设计需求

内容的提问来源于stack exchange,提问作者장서영

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:39:02