如何让代码创建的导航栏自定义按钮显示在左上角?
解决导航栏自定义返回按钮左侧间距问题
嗨,我来帮你搞定这个导航栏按钮偏右的问题~你遇到的左侧间距问题,主要是因为用UIButton作为UIBarButtonItem的customView时,系统默认会给customView加上内边距,同时UIButton自身的内容布局也没对齐到最左侧。下面给你几个可行的解决方案:
方案1:调整UIButton的内边距与内容对齐
直接修改按钮的内容对齐方式和内边距,把内容推到最左侧:
let button = UIButton(type: .system) button.frame = CGRect(x: 0, y: 0, width: 60, height: 40) // 适当加宽避免文字截断 button.setTitle("Back", for: .normal) button.setImage(UIImage(named: "ic_keyboard_arrow_left_2x"), for: .normal) // 核心:让按钮内容靠左对齐 button.contentHorizontalAlignment = .left // 调整内边距,抵消系统默认的左侧间距 button.contentEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0) // 可选:调整图片和文字的间距 button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8) let barButton = UIBarButtonItem(customView: button) self.navigationItem.leftBarButtonItem = barButton
方案2:直接使用系统UIBarButtonItem初始化方法(推荐)
如果不需要复杂的自定义样式,用系统自带的初始化方法最省心,它会自动适配导航栏布局,不会出现间距问题:
if let backImage = UIImage(named: "ic_keyboard_arrow_left_2x") { let barButton = UIBarButtonItem(image: backImage, style: .plain, target: self, action: #selector(backTapped)) barButton.title = "Back" self.navigationItem.leftBarButtonItem = barButton } // 记得实现点击回调 @objc private func backTapped() { navigationController?.popViewController(animated: true) }
方案3:给customView添加Auto Layout约束
如果必须用自定义按钮,也可以通过约束强制控制布局,摆脱系统默认的间距:
let button = UIButton(type: .system) button.setTitle("Back", for: .normal) button.setImage(UIImage(named: "ic_keyboard_arrow_left_2x"), for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.contentHorizontalAlignment = .left let barButton = UIBarButtonItem(customView: button) self.navigationItem.leftBarButtonItem = barButton // 添加约束固定按钮尺寸和位置逻辑 NSLayoutConstraint.activate([ button.widthAnchor.constraint(equalToConstant: 60), button.heightAnchor.constraint(equalTo: navigationController!.navigationBar.heightAnchor) ])
总结一下,方案2是最推荐的,因为系统已经帮我们处理了所有导航栏的布局细节;如果一定要用自定义按钮,方案1和3都能有效解决左侧间距问题,你可以根据自己的需求选择~
内容的提问来源于stack exchange,提问作者Swift_prasad
相关产品推荐
相关产品推荐

