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

UIKit开发:如何调整ViewController尺寸适配UISplitViewController主列

CalendarViewController适配iPad分屏主列修改方案
  • 首先配置UISplitViewController的主列尺寸规则
    在makeSplitViewController方法中新增主列宽范围配置,避免默认宽度超出日历的适配范围:
splitViewController.preferredPrimaryColumnWidthFraction = 0.3
splitViewController.minimumPrimaryColumnWidth = 280
splitViewController.maximumPrimaryColumnWidth = 400
  • 修正CalendarViewController的布局约束
    重写CalendarViewController的viewDidLoad方法,将日历核心视图的约束绑定到父视图的安全区,替换原有可能存在的固定宽高配置:
override func viewDidLoad() {
    super.viewDidLoad()
    calendarView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        calendarView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
        calendarView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        calendarView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        calendarView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
    ])
}
  • 监听容器尺寸变化主动刷新布局
    重写CalendarViewController的尺寸变化回调方法,每次分屏宽度改动时触发日历视图重绘:
override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    calendarView.reloadData()
}

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    if traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass {
        calendarView.reloadData()
    }
}
  • 动态调整日历元素尺寸
    修改日历数据源配置,根据当前容器宽度动态调整时间列、事件单元格等元素的尺寸,避免窄屏下元素溢出:
func timeColumnWidth(_ timelineView: TimelineView) -> CGFloat {
    return view.bounds.width < 320 ? 40 : 60
}

func eventCellHeight(_ event: EventDescriptor) -> CGFloat {
    return view.bounds.width < 320 ? 24 : 30
}
  • 调整边距适配导航栏
    确认UINavigationController和CalendarViewController的内边距适配规则,避免日历内容被导航栏遮挡:
override func viewDidLoad() {
    super.viewDidLoad()
    automaticallyAdjustsScrollViewInsets = true
    additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:36:03