Swift中BubbleTabBarController切换标签时导航栏标题图片位置偏移问题
问题解决方法
这个偏移本质是导航栏布局变动时,自定义titleView的布局规则不明确,加上标签切换过程中导航栏的边距计算异常导致的,以下是可落地的解决方案:
- 方案1:替换固定frame的titleView为自动约束版本
原来的写法直接给UIImageView写死frame,导航栏布局刷新时会丢失位置参考,改成用约束定义尺寸,不需要指定origin即可解决大部分偏移问题:
func setOtherNavigation(){ let navBar = self.navigationController!.navigationBar // 导航栏外观建议移到AppDelegate全局配置,避免每个页面重复设置 let standardAppearance = UINavigationBarAppearance() standardAppearance.configureWithOpaqueBackground() standardAppearance.backgroundImage = UIImage(named: "top_bar") let compactAppearance = standardAppearance.copy() compactAppearance.backgroundImage = UIImage(named: "top_bar") navBar.standardAppearance = standardAppearance navBar.scrollEdgeAppearance = standardAppearance navBar.compactAppearance = compactAppearance // 优化titleView配置 let imgLogo = UIImageView() imgLogo.translatesAutoresizingMaskIntoConstraints = false imgLogo.contentMode = .scaleAspectFit imgLogo.image = UIImage(named: "logo") // 只定尺寸,origin由导航栏自动计算 NSLayoutConstraint.activate([ imgLogo.widthAnchor.constraint(equalToConstant: 200), imgLogo.heightAnchor.constraint(equalToConstant: 40) ]) self.navigationItem.titleView = imgLogo }
- 方案2:统一所有标签页的导航栏左右边距
如果不同标签页的leftBarButtonItem/rightBarButtonItem数量、宽度不一致,会导致导航栏中间title区域的可用宽度变化,触发偏移。可以给没有侧边按钮的页面添加固定宽度的占位按钮,保证所有标签页边距统一:
// 在没有左侧按钮的页面viewDidLoad中添加占位 let leftPlaceholder = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) leftPlaceholder.width = 40 // 和有左侧按钮的页面边距保持一致 self.navigationItem.leftBarButtonItem = leftPlaceholder // 右侧同理,没有按钮的话也加对应宽度的占位 let rightPlaceholder = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) rightPlaceholder.width = 40 self.navigationItem.rightBarButtonItem = rightPlaceholder
- 方案3:调整配置调用时机
将setOtherNavigation的调用从viewDidLoad移到viewWillAppear(_ animated: Bool)中,保证每次页面切换显示时,导航栏配置都会重新生效,避免切换过程中缓存的布局参数影响。
内容的提问来源于stack exchange,提问作者Noorul
相关产品推荐
相关产品推荐

