iOS:为导航栏标题视图添加带约束的图片与文字
自定义导航栏标题视图(左侧图片+右侧文字)
我帮你把这个自定义标题视图的代码补全并整理好了,这样你可以直接用来实现导航栏里图片+文字的标题效果:
class CustomTitleView: UIView { // 自定义文字标签,你可以根据需求调整CustomLabel的样式 var titleLabel = CustomLabel() // 左侧图片视图 var leftImageView = UIImageView() override init(frame: CGRect){ super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder){ super.init(coder: aDecoder) setupSubviews() } // 初始化子视图 private func setupSubviews(){ // 配置图片视图基础属性 leftImageView.contentMode = .scaleAspectFit leftImageView.clipsToBounds = true // 配置标签基础属性 titleLabel.textAlignment = .left titleLabel.numberOfLines = 1 // 添加子视图到父视图 addSubview(leftImageView) addSubview(titleLabel) // 开启自动布局 leftImageView.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false } // 加载标题内容和图片的方法 func loadWith(title: String, image: UIImage) { titleLabel.text = title leftImageView.image = image // 设置自动布局约束,确保图片和文字正确排列 NSLayoutConstraint.activate([ // 图片视图约束:垂直居中、左对齐父视图、固定宽高 leftImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor), leftImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor), leftImageView.widthAnchor.constraint(equalToConstant: 24), leftImageView.heightAnchor.constraint(equalToConstant: 24), // 文字标签约束:垂直居中、左侧与图片保持间距、右对齐父视图 titleLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor), titleLabel.leadingAnchor.constraint(equalTo: leftImageView.trailingAnchor, constant: 8), titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor), titleLabel.heightAnchor.constraint(equalTo: self.heightAnchor) ]) } } // 示例自定义标签类,可按需修改样式 class CustomLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) setupStyle() } required init?(coder: NSCoder) { super.init(coder: coder) setupStyle() } private func setupStyle() { font = UIFont.systemFont(ofSize: 17, weight: .medium) textColor = .black } }
使用方法
在你的ViewController里,这样设置导航栏标题:
override func viewDidLoad() { super.viewDidLoad() let customTitleView = CustomTitleView(frame: CGRect(x: 0, y: 0, width: 200, height: 44)) // 替换成你的标题文字和图片 customTitleView.loadWith(title: "我的自定义标题", image: UIImage(named: "icon_title")!) navigationItem.titleView = customTitleView }
关键点说明
- 补全了自动布局约束,这是原代码缺失的核心部分,确保图片和文字能稳定排列
- 把变量名改成了更符合Swift规范的小驼峰格式,代码可读性更强
- 拆分了初始化逻辑,用
setupSubviews专门处理子视图配置,结构更清晰 - 你可以根据需求调整图片宽高、文字图片间距,以及
CustomLabel的字体、颜色等样式
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

