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

Swift开发:如何在UINavigationBar左侧添加图片与文本,现有代码不生效

modelNavigationBar

问题原因

你当前的代码存在以下几个问题导致无法实现预期效果:

  • 重复对navigationItem.leftBarButtonItem赋值,仅最后一次赋值会生效
  • 没有将头像图片和用户文本两个控件封装到同一个容器视图中,单个leftBarButtonItem只能加载一个自定义视图
  • 额外设置了navigationItem.titleView为图片,会覆盖导航栏中间的标题位置,如果不需要在导航栏中间显示图片可以删除这段逻辑
修复后的实现代码

你可以创建一个容器UIView,同时把头像的UIImageView和用户名的UILabel添加到容器内,再将容器整体设置为leftBarButtonItem的自定义视图即可,参考代码如下:

private func configureItems(){
    // 右侧添加按钮保留
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
    
    // 创建左侧自定义容器视图,宽高可以根据自己需求调整
    let leftContainer = UIView(frame: CGRect(x: 0, y: 0, width: 140, height: 40))
    
    // 添加头像视图
    let avatarImageView = UIImageView(image: UIImage(named: "image8"))
    avatarImageView.frame = CGRect(x: 0, y: 2.5, width: 35, height: 35)
    avatarImageView.contentMode = .scaleAspectFill
    avatarImageView.layer.cornerRadius = 17.5 // 圆形头像,不需要可以删掉
    avatarImageView.layer.masksToBounds = true
    leftContainer.addSubview(avatarImageView)
    
    // 添加用户名标签
    let nameLabel = UILabel(frame: CGRect(x: 45, y: 0, width: 90, height: 40))
    nameLabel.text = "John Doe"
    nameLabel.textAlignment = .left
    nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
    leftContainer.addSubview(nameLabel)
    
    // 将容器设置为左侧按钮的自定义视图
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftContainer)
    
    // 如果不需要导航栏中间显示图片,下面这段设置titleView的代码可以删掉
    // let navController = navigationController!
    // let image = UIImage(named: "image8")!
    // let imageView = UIImageView(image: image)
    // let bannerWidth = navController.navigationBar.frame.size.width
    // let bannerHeight = navController.navigationBar.frame.size.height
    // imageView.frame = CGRect(x: 0, y: 0, width: bannerWidth, height: bannerHeight)
    // imageView.contentMode = .scaleAspectFit
    // imageView.center = navController.navigationBar.center
    // navigationItem.titleView = imageView
}

如果发现左侧视图位置太靠边缘,可以添加偏移调整:

// 调整左侧按钮的内边距,向左/右偏移可以修改负/正数
navigationItem.leftBarButtonItem?.imageInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)

内容的提问来源于stack exchange,提问作者JESTIN SAJI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:39:04