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

Swift:适配iPad屏幕调整NavigationBar尺寸及字体

嘿,这个iPad导航栏适配的问题我之前踩过坑!正好有几个实用的解决办法,不管是用Storyboard可视化配置还是写代码都能搞定,来看看:

方法1:用Storyboard的Size Class做针对性适配

这是最直观的可视化操作方式,不用写代码就能搞定:

  • 打开你的Storyboard,选中目标NavigationBar或者对应的Navigation Controller
  • 点击Storyboard底部的Size Class切换按钮(默认显示wAny hAny),选择iPad对应的wRegular hRegular(这是iPad的默认Size Class)
  • 切换到Size Inspector,修改NavigationBar的Height值(默认iPhone是44,iPad可以改成56、64这类更合适的尺寸)
  • 再切换到Attributes Inspector,找到Title Text Attributes,在Font选项里设置更大的字号——注意一定要在wRegular hRegular的Size Class下设置,这样只会影响iPad的显示,不会改动iPhone上的正常效果
方法2:用代码动态适配(适合更灵活的场景)

如果需要更灵活的控制,比如根据不同iPad型号调整,或者和其他逻辑联动,就用代码来实现:

Swift版本

在ViewController的viewWillAppear方法里添加:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    // 判断当前设备是否是iPad
    if UIDevice.current.userInterfaceIdiom == .pad {
        // 调整导航栏高度
        navigationController?.navigationBar.frame.size.height = 64
        // 自定义标题字体大小和样式
        let titleAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 22, weight: .semibold)]
        navigationController?.navigationBar.titleTextAttributes = titleAttrs
    }
}

Objective-C版本

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        // 调整导航栏高度
        self.navigationController.navigationBar.frame.size.height = 64;
        // 设置标题字体
        NSDictionary *titleAttrs = @{NSFontAttributeName: [UIFont systemFontOfSize:22 weight:UIFontWeightSemibold]};
        self.navigationController.navigationBar.titleTextAttributes = titleAttrs;
    }
}
方法3:使用动态字体(推荐,符合苹果设计规范)

苹果官方推荐用动态字体来做适配,不仅能自动适配iPad的大尺寸,还能尊重用户在系统设置里调整的字体大小偏好:

  • 在Storyboard里:选中NavigationBar的Title Text Attributes,Font选择Dynamic Type分类下的字体(比如Title 1),系统会自动根据设备和用户偏好调整大小
  • 用代码设置的话:
override func viewDidLoad() {
    super.viewDidLoad()
    // 使用系统动态字体
    let dynamicTitleFont = UIFont.preferredFont(forTextStyle: .title1)
    navigationController?.navigationBar.titleTextAttributes = [.font: dynamicTitleFont]
}

小提示

如果调整导航栏高度后发现页面内容被遮挡,可以在ViewController里添加一行代码调整布局:

edgesForExtendedLayout = .bottom

这样内容就会自动避开导航栏的区域啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:57:51