2301_77192008头像

自定义Tabbar和导航栏 适配 iPhone Duo 实践 iPhone Duo 适配

自定义Tabbar和导航栏 适配 iPhone Duo 实践 iPhone Duo 适配

使用范围

本文是一份独立的 UIKit 接入指南,说明 iPhone Duo 的窗口、安全区、导航栏、底部 Tab 和页面容器适配。。示例使用通用类型和占位内容,可按需复制到新建的 iOS App。

安全区阈值和示例布局尺寸是演示取值,应结合目标系统版本、实际设备和设计规范验证,不能将其视为系统承诺的固定尺寸。

1. 快速开始:独立接入需要哪些文件

新项目只需要准备以下四个独立模块:

DuoLayout.swift              // 安全区、侧栏和顶部系统图标计算
DuoViewController.swift      // 页面基类:导航栏、状态栏、布局刷新
DuoNavigationController.swift // 导航栈:侧栏返回按钮和内容 frame
DuoTabBarController.swift    // 首页/个人中心:底部 Dock 和侧栏 Dock

如果只需要适配一个页面,可以先引入 DuoLayout.swift 和下面的“页面基类”示例;如果需要首页、个人中心和二级页面,再引入导航容器和 Dock 示例。

建议最低部署版本为 iOS 17;reservedRegions 和 verticalBarEdge 示例使用 iOS 27.1 的可用性判断,因此旧系统会自动走安全区兜底策略。

2. Duo 的三种主要姿态

姿态系统安全区特征页面内容区导航栏Tab / Dock状态栏图标
普通 iPhone左右安全区不足以形成侧栏使用完整窗口宽度位于顶部安全区下方底部横向跟随页面
Duo 展开竖屏顶部安全区较高,左右没有侧栏使用完整窗口宽度嵌入顶部状态区,与状态区同高;右侧避开系统图标底部横向跟随页面
Duo 展开横屏 / 折叠外屏左侧或右侧安全区通常不小于 44pt扣除侧栏安全区后的内容区域位于内容区域顶部系统状态栏侧栏内竖向排列固定黑色

侧栏不应通过设备型号、屏幕宽高或横竖屏名称推断。推荐以 safeAreaInsets.left/right 为主判定依据,再用 verticalBarEdge 在左右都有足够空间时消歧。

3. 适配总体架构

推荐将适配职责拆分为四层:

SceneDelegate
    └── 根容器选择
        ├── 登录:DuoNavigationController
        └── 已登录:DuoTabBarController
                ├── DuoNavigationController + 首页
                └── DuoNavigationController + 个人中心

DuoLayout
    ├── 判断是否存在侧栏
    ├── 计算内容区和侧栏区 frame
    ├── 计算顶部系统图标占用宽度
    ├── 计算侧栏按钮起点
    └── 计算底部滚动留白

DuoViewController
    ├── 导航栏和状态区
    ├── 状态栏样式
    ├── 页面是否铺满窗口
    └── safeArea / trait 变化刷新

DuoNavigationController / DuoTabBarController
    ├── 调整子页面 frame
    ├── 处理导航栏侧栏化
    ├── 处理 Tab 横向 / 竖向切换
    └── 控制侧栏按钮和底色补条

后文的 DuoLayout、DuoViewController、DuoNavigationController 和 DuoTabBarController 示例分别对应上述职责;示例页面演示登录、首页、二级页和个人中心之间的流转。

4. 侧栏判断和 frame 计算

4.1 侧栏方向

示例使用 44pt 作为侧栏候选阈值:

if insets.right >= spanGate && insets.right >= insets.left {
    return .trailing
}
if insets.left >= spanGate {
    return .leading
}
return .none

后文的 DuoLayout.railSide(insets:traits:) 按以下顺序判定:

  1. 右侧安全区达到阈值且不小于左侧,判定为右侧栏。
  2. 否则左侧安全区达到阈值,判定为左侧栏。
  3. 两侧都不足阈值,判定为无侧栏。
  4. iOS 27.1 及以上,如果 verticalBarEdge 明确指出方向,则用它消除左右同时存在时的歧义。

不要单独依赖 verticalBarEdge。内屏竖屏可能返回 preferred edge,但此时实际工具栏仍然是顶部横向布局。

4.2 内容区和侧栏区

有侧栏时,页面内容不能画入系统状态栏列:

static func contentFrame(in bounds: CGRect,
                         insets: UIEdgeInsets,
                         traits: UITraitCollection? = nil) -> CGRect
  • 无侧栏:返回完整 bounds。
  • 左侧栏:x 增加 insets.left,宽度减去左侧安全区。
  • 右侧栏:宽度减去 insets.right。
  • 高度始终保持窗口高度。

侧栏自身使用独立 frame:

static func railFrame(in bounds: CGRect,
                      insets: UIEdgeInsets,
                      traits: UITraitCollection? = nil) -> CGRect

这个区域用于放置导航操作按钮、竖向 Dock,以及顶部导航底色补条。

4.3 登录页的全屏例外

登录页通常需要铺满窗口,避免进入侧栏姿态后顶部背景被裁切。可通过页面基类的 fillsWindow 表达这个例外:

override var fillsWindow: Bool {
    return true
}

普通首页和个人中心使用 contentFrame 收窄;登录页使用完整窗口 frame,但登录表单内部仍然根据安全区摆放。

5. 顶部导航和系统状态区

5.1 普通姿态

普通姿态下,导航栏位于 safeAreaLayoutGuide.topAnchor 下方,导航高度使用固定的业务导航高度。页面内容从导航栏底部开始。

5.2 Duo 展开竖屏

展开竖屏时,顶部安全区高度较大,但左右没有侧栏。此时导航栏嵌入顶部状态区:

navigationBar.top    = view.top
navigationBar.bottom = safeAreaLayoutGuide.top

导航栏右侧还要避开系统状态图标。iOS 27.1 及以上可以读取 reservedRegions(kind: .occlusion),将带 margins 的区域收缩成图标本体,再计算右侧需要保留的宽度。

后文的通用实现提供:

  • DuoLayout.topTrailingClearance(in:)
  • DuoLayout.shouldEmbedNavigationInStatusArea(_:)

5.3 Duo 横屏和折叠外屏

存在侧栏时,页面自己的顶部导航只保留标题和内容导航区域;返回等导航操作按钮移到侧栏。侧栏顶部可增加与导航栏同色的背景区域,避免内容区和系统状态栏列之间出现断色。

当页面背景较深或页面顶部为主题色时,侧栏补色要跟随当前页面导航栏,而不是固定使用白色。

6. 登录页适配

登录页的原则:

  • 页面背景铺满全屏。
  • 状态栏颜色由登录页自己控制,不被侧栏默认黑色策略覆盖。
  • 顶部表单内容仍然位于安全域内。
  • 外屏和内屏竖屏下,右上角或侧边系统图标区域不能被表单按钮覆盖。
  • 姿态变化后重新计算图标和表单元素位置。

登录页可以设置:

override var fillsWindow: Bool { true }
override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }

示例登录页只使用本地静态表单,没有网络校验或 Loading。表单布局可以在自定义 view 的 layoutSubviews 或控制器的 viewDidLayoutSubviews 中根据实时安全区刷新。

7. 一级页面适配

一级页面包括首页和个人中心,通常包含:

  • 顶部品牌或标题区域。
  • 可滚动内容区域。
  • 底部横向 Dock,或 Duo 侧栏中的竖向 Dock。

布局规则:

无侧栏

页面内容 = 顶部导航下方
滚动区域底部 = safeArea.bottom + 横向 Dock 高度 + 必要间距
Dock = 页面底部横向居中

有侧栏

页面 frame = contentFrame
滚动区域底部 = safeArea.bottom + 无底部安全区时的兜底间距
Dock = 侧栏中部竖向排列

可以通过 DuoLayout.bottomContentReserve(in:) 统一计算列表底部留白:无侧栏时预留横向 Dock,有侧栏时不再重复预留横向高度。

在 Tab 容器的 viewDidLayoutSubviews() 中根据 DuoLayout.railSide(insets:traits:) 切换横向和竖向 Dock,避免各业务页面重复处理。

8. UINavigationController 基类

DuoNavigationController 负责页面栈和侧栏导航:

8.1 监听 trait 和安全区

if #available(iOS 27.1, *) {
    registerForTraitChanges(
        UITraitCollection.systemTraitsAffectingVerticalBarEdge
    ) { [weak self] (_: DuoNavigationController, _: UITraitCollection) in
        self?.view.setNeedsLayout()
    }
}

override func viewSafeAreaInsetsDidChange() {
    super.viewSafeAreaInsetsDidChange()
    view.setNeedsLayout()
}

8.2 在布局阶段调整子页面

viewWillLayoutSubviews 中先把页面 frame 调整到目标区域,避免 push/pop 动画开始时短暂全屏再被收窄。

viewDidLayoutSubviews 中完成:

  1. 读取最新安全区并写入共享状态。
  2. 按 contentFrame 调整子页面 frame。
  3. fillsWindow == true 的页面使用完整窗口。
  4. 有侧栏时隐藏页面自己的返回按钮。
  5. 在侧栏放置返回按钮。
  6. 补齐侧栏顶部背景,并将侧栏控件提到最前面。

当导航控制器嵌套在 Tab 容器中时,应明确侧栏控件的所有权:导航控制器负责侧栏返回按钮,Tab 容器负责侧栏 Dock。两者不能重复绘制同一按钮或重复扣减侧栏宽度。

9. UIViewController 页面基类

DuoViewController 负责页面级状态和导航约束。

9.1 页面状态属性

建议提供以下能力:

属性作用
showsNavigationBar页面是否显示顶部导航
showsBackButton是否显示返回操作
fillsWindow是否忽略侧栏内容收窄
preferredStatusBarStyle页面需要覆盖默认状态栏样式时使用
railIsManagedByParent侧栏存在时通知子页面隐藏内置返回按钮

9.2 状态栏样式

有侧栏时,系统状态栏位于左右侧栏,固定使用深色图标;无侧栏时,状态栏样式跟随当前页面。登录页等深色背景页面可以通过 keepsPageStatusStyle 保持浅色图标。

9.3 布局刷新时机

不要只在 traitCollectionDidChange(_:) 里读取安全区。trait 回调触发时,safeAreaInsets 可能仍是旧值。推荐:

override func viewSafeAreaInsetsDidChange() {
    super.viewSafeAreaInsetsDidChange()
    view.setNeedsLayout()
    refreshStatusBarPose()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    refreshStripLayout()
    refreshStatusBarPose()
}

registerForTraitChanges 用来触发重新布局;真正依赖最新安全区的 frame 和颜色更新放在布局阶段完成。

需要关注的变化包括:顶部状态区高度、Dynamic Island 状态、左右系统栏、横竖屏切换、折叠和展开、铰链区域变化以及弹窗导致的安全区变化。

10. UITabBarController 基类

DuoTabBarController 隐藏系统 TabBar,使用自定义 DuoDockView:

tabBar.isHidden = true

10.1 监听变化

if #available(iOS 27.1, *) {
    registerForTraitChanges(
        UITraitCollection.systemTraitsAffectingVerticalBarEdge
    ) { [weak self] (_: DuoTabBarController, _: UITraitCollection) in
        self?.view.setNeedsLayout()
    }
}

override func viewSafeAreaInsetsDidChange() {
    super.viewSafeAreaInsetsDidChange()
    view.setNeedsLayout()
}

10.2 viewDidLayoutSubviews 处理顺序

推荐顺序:

  1. 确保系统 TabBar 隐藏。
  2. 更新共享安全区缓存。
  3. 调整所有子导航控制器的内容 frame。
  4. 根据侧栏状态切换 Dock 横向/竖向布局。
  5. 更新侧栏导航按钮。
  6. 根据当前页面背景色更新容器背景。
  7. 更新侧栏顶部底色补条。
  8. 将补条、侧栏按钮和 Dock 提到最前面。

10.3 页面栈和 Dock 的关系

首页和个人中心处于导航栈根页面时显示 Dock;进入首页二级页后隐藏 Dock,返回根页面时重新显示。可通过 UINavigationControllerDelegate 的 willShow / didShow 处理这个状态。

11. 全局适配要点

11.1 安全区缓存

安全区会随姿态实时变化,不能只在启动时读取一次。布局时从当前容器的 view.safeAreaInsets 获取最新值;如果已有代码必须使用共享缓存,应在安全区变化后更新缓存,且不要让缓存成为布局的唯一数据源。

11.2 屏幕尺寸

涉及页面尺寸时,应使用实时计算的 view/window bounds。内屏横屏时要扣除侧栏状态区,不能无条件使用 UIScreen.main.bounds.width 作为业务内容宽度。

11.3 导航内容

有侧栏时,页面内的返回按钮应隐藏,只保留标题;侧栏导航控件统一负责返回。姿态变化后要重新计算显示状态和位置。

11.4 底部 Tab

有侧栏时 Dock 竖向放入侧栏;无侧栏时 Dock 横向放在底部。切换布局时必须同时更新:

  • Dock frame。
  • 按钮排列方向。
  • 滚动区域底部留白。
  • 页面和 Dock 的层级关系。

12. 通用模块职责

适配能力独立示例中的入口
侧栏方向、内容区和侧栏区计算DuoLayout.railSide、contentFrame、railFrame
顶部系统图标避让DuoLayout.topTrailingClearance 和 reservedRegions
顶部导航嵌入状态区DuoLayout.embedsNavigationInStatusArea
页面导航与状态栏DuoViewController
导航栈与侧栏返回DuoNavigationController
横向/竖向 DockDuoTabBarController 和 DuoDockView
页面流转LoginViewController、HomeViewController、HomeDetailViewController、ProfileViewController

13. 接入现有工程的建议

  1. 将侧栏判定和 frame 计算集中在 DuoLayout,不要在业务页面重复判断屏幕尺寸。
  2. 让统一页面基类管理顶部导航、返回、状态栏和背景策略。
  3. 让 Tab 容器负责横向/竖向 Dock,导航容器负责页面栈和侧栏返回按钮。
  4. 在导航控制器和 Tab 容器中注册 systemTraitsAffectingVerticalBarEdge。
  5. 在 viewSafeAreaInsetsDidChange 和 viewDidLayoutSubviews 中刷新约束及滚动区域底部留白。
  6. 对登录、相机、WebView、底部弹框等铺满窗口的页面单独声明全屏策略。
  7. 所有从顶部或底部贴边的 UI,都使用实时 safeAreaInsets,避免缓存启动时的值。
  8. 在普通姿态、展开竖屏、展开横屏、折叠外屏之间反复切换,验证 push/pop、Tab 切换、滚动和弹框。

14. 验收清单

  • 普通 iPhone:导航栏在顶部,Dock 在底部横向排列。
  • Duo 展开竖屏:导航栏嵌入顶部状态区,右侧不遮挡系统图标,Dock 仍在底部。
  • Duo 展开横屏:页面内容扣除侧栏,Dock 变为侧栏竖向排列。
  • Duo 折叠外屏:行为与有侧栏的横屏姿态一致。
  • 登录页背景铺满窗口,状态栏样式不被侧栏策略错误覆盖。
  • 首页和个人中心滚动内容不会被底部 Dock 遮挡。
  • 首页进入二级页面后 Dock 隐藏,返回后恢复。
  • 侧栏姿态下页面内返回按钮不会和侧栏按钮重复显示。
  • 姿态切换后安全区、导航、Dock、滚动区域和状态栏颜色立即刷新。
  • 工程不依赖网络请求、Loading 或业务数据也能完整演示 UI 流程。

15. 独立实现:DuoLayout

下面的类型只依赖 UIKit,不需要第三方库或特定业务模块。

15.1 侧栏方向和内容 frame

import UIKit

enum DuoRailSide: Equatable {
    case none
    case leading
    case trailing
}

enum DuoLayout {
    /// 普通刘海/横屏安全区不应被误判为 Duo 侧栏。
    static let railThreshold: CGFloat = 44

    static func railSide(
        insets: UIEdgeInsets,
        traits: UITraitCollection? = nil
    ) -> DuoRailSide {
        let fallback: DuoRailSide
        if insets.right >= railThreshold && insets.right >= insets.left {
            fallback = .trailing
        } else if insets.left >= railThreshold {
            fallback = .leading
        } else {
            fallback = .none
        }

        guard fallback != .none else { return .none }

        // verticalBarEdge 只能用于左右都有足够空间时的方向消歧,
        // 不能单独用它判断当前是否存在侧栏。
        if #available(iOS 27.1, *), let traits,
           insets.left >= railThreshold, insets.right >= railThreshold {
            switch traits.verticalBarEdge {
            case .leading:
                return .leading
            case .trailing:
                return .trailing
            case .unspecified:
                return fallback
            @unknown default:
                return fallback
            }
        }
        return fallback
    }

    static func contentFrame(
        in bounds: CGRect,
        insets: UIEdgeInsets,
        traits: UITraitCollection? = nil
    ) -> CGRect {
        switch railSide(insets: insets, traits: traits) {
        case .none:
            return bounds
        case .leading:
            return CGRect(
                x: bounds.minX + insets.left,
                y: bounds.minY,
                width: max(0, bounds.width - insets.left),
                height: bounds.height
            )
        case .trailing:
            return CGRect(
                x: bounds.minX,
                y: bounds.minY,
                width: max(0, bounds.width - insets.right),
                height: bounds.height
            )
        }
    }

    static func railFrame(
        in bounds: CGRect,
        insets: UIEdgeInsets,
        traits: UITraitCollection? = nil
    ) -> CGRect {
        switch railSide(insets: insets, traits: traits) {
        case .none:
            return .zero
        case .leading:
            return CGRect(x: bounds.minX, y: bounds.minY,
                          width: insets.left, height: bounds.height)
        case .trailing:
            return CGRect(x: bounds.maxX - insets.right, y: bounds.minY,
                          width: insets.right, height: bounds.height)
        }
    }
}

15.2 顶部系统图标避让

展开竖屏时,导航栏仍然在顶部,但右上角可能存在系统图标遮挡区。不要根据固定机型坐标避让,直接读取系统提供的 reserved region:

extension DuoLayout {
    static func topTrailingClearance(in view: UIView) -> CGFloat {
        guard #available(iOS 27.1, *) else { return 0 }

        let topBand = CGRect(
            x: 0,
            y: 0,
            width: view.bounds.width,
            height: max(view.safeAreaInsets.top, 1)
        )
        var clearance: CGFloat = 0

        for region in view.reservedRegions(kind: .occlusion) where region.isActive {
            // region.frame 通常包含 margins,使用收缩后的图标本体矩形。
            let iconFrame = region.frame.inset(by: region.margins)
            guard iconFrame.intersects(topBand) else { continue }
            guard iconFrame.minX >= view.bounds.width * 0.45 else { continue }
            clearance = max(clearance, view.bounds.maxX - iconFrame.minX + 8)
        }
        return clearance
    }

    static func embedsNavigationInStatusArea(_ view: UIView) -> Bool {
        let side = railSide(insets: view.safeAreaInsets,
                            traits: view.traitCollection)
        guard side == .none else { return false }
        guard view.safeAreaInsets.top >= railThreshold else { return false }
        return topTrailingClearance(in: view) >= railThreshold
    }
}

15.3 侧栏按钮起点

侧栏中的导航按钮应放在系统状态图标簇下方,而不是直接使用整段 occlusion frame 的 maxY:

extension DuoLayout {
    static func railButtonTop(in view: UIView) -> CGFloat {
        let rail = railFrame(in: view.bounds,
                             insets: view.safeAreaInsets,
                             traits: view.traitCollection)
        guard rail.width > 0 else { return 0 }

        var iconBottom: CGFloat = 0
        if #available(iOS 27.1, *) {
            for region in view.reservedRegions(kind: .occlusion)
            where region.isActive {
                let icon = region.frame.inset(by: region.margins)
                guard icon.intersects(rail.insetBy(dx: -1, dy: -1)) else {
                    continue
                }
                guard icon.minY < rail.height * 0.6 else { continue }
                iconBottom = max(iconBottom, icon.maxY)
            }
        }

        // 旧系统或暂时读不到 reserved region 时的保守兜底。
        return (iconBottom > 0 ? iconBottom : 82) + 8
    }
}

16. 独立实现:页面基类

页面基类统一处理顶部导航、状态栏和安全区变化。业务页面只负责创建内容,不重复写 Duo 判断。

import UIKit

class DuoViewController: UIViewController {
    let navigationBar = UIView()
    let titleLabel = UILabel()
    let contentView = UIView()
    let backButton = UIButton(type: .system)

    var navigationTitle = "" {
        didSet { titleLabel.text = navigationTitle }
    }
    var showsNavigationBar = true
    var showsBackButton = true

    /// 登录、相机、全屏引导页可覆盖为 true。
    var fillsWindow: Bool { false }
    var railIsManagedByParent = false {
        didSet {
            if oldValue != railIsManagedByParent, isViewLoaded {
                view.setNeedsLayout()
                setNeedsStatusBarAppearanceUpdate()
            }
        }
    }

    private var topConstraint: NSLayoutConstraint?
    private var bottomConstraint: NSLayoutConstraint?
    private var heightConstraint: NSLayoutConstraint?
    private var trailingConstraint: NSLayoutConstraint?
    private var lastEmbedded = false
    private var lastClearance: CGFloat = -1

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground
        setupNavigationBar()
        setupContentView()
        watchDuoTraits()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
        refreshDuoLayout()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // trait 回调触发时 safeAreaInsets 可能仍是旧值,
        // 因此最终约束刷新放在布局阶段。
        refreshDuoLayout()
    }

    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        view.setNeedsLayout()
        refreshDuoLayout()
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        !railIsManagedByParent && DuoLayout.embedsNavigationInStatusArea(view)
            ? .lightContent : .darkContent
    }

    func handleBack() {
        navigationController?.popViewController(animated: true)
    }

    private func setupNavigationBar() {
        navigationBar.translatesAutoresizingMaskIntoConstraints = false
        navigationBar.backgroundColor = .systemOrange
        navigationBar.isHidden = !showsNavigationBar
        view.addSubview(navigationBar)

        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.textColor = .white
        titleLabel.font = .systemFont(ofSize: 18, weight: .bold)
        titleLabel.textAlignment = .center
        navigationBar.addSubview(titleLabel)

        backButton.translatesAutoresizingMaskIntoConstraints = false
        backButton.setImage(UIImage(systemName: "chevron.left"),
                            for: .normal)
        backButton.tintColor = .white
        backButton.addTarget(self, action: #selector(backTapped),
                             for: .touchUpInside)
        backButton.isHidden = !showsBackButton
        navigationBar.addSubview(backButton)

        topConstraint = navigationBar.topAnchor.constraint(
            equalTo: view.safeAreaLayoutGuide.topAnchor)
        heightConstraint = navigationBar.heightAnchor.constraint(equalToConstant: 52)
        trailingConstraint = navigationBar.trailingAnchor.constraint(
            equalTo: view.trailingAnchor)
        topConstraint?.isActive = true
        heightConstraint?.isActive = true
        trailingConstraint?.isActive = true

        NSLayoutConstraint.activate([
            navigationBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            backButton.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor,
                                                constant: 8),
            backButton.centerYAnchor.constraint(equalTo: navigationBar.centerYAnchor),
            backButton.widthAnchor.constraint(equalToConstant: 44),
            backButton.heightAnchor.constraint(equalToConstant: 44),
            titleLabel.centerXAnchor.constraint(equalTo: navigationBar.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: navigationBar.centerYAnchor),
            titleLabel.leadingAnchor.constraint(
                greaterThanOrEqualTo: backButton.trailingAnchor, constant: 8),
            titleLabel.trailingAnchor.constraint(
                lessThanOrEqualTo: navigationBar.trailingAnchor, constant: -12)
        ])
    }

    private func setupContentView() {
        contentView.translatesAutoresizingMaskIntoConstraints = false
        view.insertSubview(contentView, belowSubview: navigationBar)
        NSLayoutConstraint.activate([
            contentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            contentView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor)
        ])
    }

    private func refreshDuoLayout() {
        guard showsNavigationBar, isViewLoaded else { return }
        let hasRail = railIsManagedByParent ||
            DuoLayout.railSide(insets: view.safeAreaInsets,
                                traits: view.traitCollection) != .none
        backButton.isHidden = !showsBackButton || hasRail
        let embedded = !railIsManagedByParent &&
            DuoLayout.embedsNavigationInStatusArea(view)
        let clearance = embedded ? DuoLayout.topTrailingClearance(in: view) : 0
        guard embedded != lastEmbedded || abs(clearance - lastClearance) > 0.5 else {
            return
        }

        lastEmbedded = embedded
        lastClearance = clearance
        topConstraint?.isActive = false
        bottomConstraint?.isActive = false
        heightConstraint?.isActive = false
        trailingConstraint?.constant = -clearance

        if embedded {
            topConstraint = navigationBar.topAnchor.constraint(equalTo: view.topAnchor)
            bottomConstraint = navigationBar.bottomAnchor.constraint(
                equalTo: view.safeAreaLayoutGuide.topAnchor)
            topConstraint?.isActive = true
            bottomConstraint?.isActive = true
        } else {
            topConstraint = navigationBar.topAnchor.constraint(
                equalTo: view.safeAreaLayoutGuide.topAnchor)
            heightConstraint = navigationBar.heightAnchor.constraint(equalToConstant: 52)
            topConstraint?.isActive = true
            heightConstraint?.isActive = true
        }

        setNeedsStatusBarAppearanceUpdate()
    }

    private func watchDuoTraits() {
        if #available(iOS 27.1, *) {
            registerForTraitChanges(
                UITraitCollection.systemTraitsAffectingVerticalBarEdge
            ) { [weak self] (_: DuoViewController, _: UITraitCollection) in
                self?.view.setNeedsLayout()
            }
        }
    }

    @objc private func backTapped() {
        handleBack()
    }
}

如果项目需要支持更早的 Swift/Xcode 版本,可用 traitCollectionDidChange(_:) 作为兼容实现,但应避免在其中直接依赖最新 safeAreaInsets;先调用 setNeedsLayout(),再在 viewDidLayoutSubviews() 读取。

17. 独立实现:导航控制器

导航控制器负责两个问题:页面栈中的子页面 frame,以及有侧栏时把返回按钮移出页面。

import UIKit

final class DuoNavigationController: UINavigationController {
    private let railBackButton = UIButton(type: .system)
    private let railContainer = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        setNavigationBarHidden(true, animated: false)
        view.backgroundColor = .systemBackground
        configureRailBackButton()
        watchDuoTraits()
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        applyChildFrame()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        applyChildFrame()
        placeRailControls()
    }

    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        view.setNeedsLayout()
    }

    override func pushViewController(_ viewController: UIViewController,
                                     animated: Bool) {
        viewController.hidesBottomBarWhenPushed = true
        super.pushViewController(viewController, animated: animated)
        applyChildFrame()
    }

    private func applyChildFrame() {
        let hasRail = DuoLayout.railSide(insets: view.safeAreaInsets,
                                         traits: traitCollection) != .none
        let frame = DuoLayout.contentFrame(
            in: view.bounds,
            insets: view.safeAreaInsets,
            traits: traitCollection
        )

        for controller in viewControllers where controller.isViewLoaded {
            if let page = controller as? DuoViewController {
                page.railIsManagedByParent = hasRail && !page.fillsWindow
            }
            if let page = controller as? DuoViewController, page.fillsWindow {
                controller.view.frame = view.bounds
            } else {
                controller.view.frame = frame
            }
        }
    }

    private func configureRailBackButton() {
        railContainer.backgroundColor = .systemOrange
        railContainer.layer.cornerRadius = 24
        railContainer.addSubview(railBackButton)
        railBackButton.translatesAutoresizingMaskIntoConstraints = false
        railBackButton.setImage(UIImage(systemName: "chevron.left"),
                                for: .normal)
        railBackButton.tintColor = .white
        railBackButton.addTarget(self, action: #selector(railBackTapped),
                                 for: .touchUpInside)
        view.addSubview(railContainer)
        NSLayoutConstraint.activate([
            railBackButton.centerXAnchor.constraint(equalTo: railContainer.centerXAnchor),
            railBackButton.centerYAnchor.constraint(equalTo: railContainer.centerYAnchor),
            railBackButton.widthAnchor.constraint(equalToConstant: 44),
            railBackButton.heightAnchor.constraint(equalToConstant: 44)
        ])
    }

    private func placeRailControls() {
        let side = DuoLayout.railSide(insets: view.safeAreaInsets,
                                      traits: traitCollection)
        guard side != .none, viewControllers.count > 1 else {
            railContainer.isHidden = true
            return
        }

        railContainer.isHidden = false
        let rail = DuoLayout.railFrame(in: view.bounds,
                                       insets: view.safeAreaInsets,
                                       traits: traitCollection)
        railContainer.frame = CGRect(
            x: rail.minX + (rail.width - 48) * 0.5,
            y: DuoLayout.railButtonTop(in: view),
            width: 48,
            height: 48
        )
        view.bringSubviewToFront(railContainer)
    }

    private func watchDuoTraits() {
        if #available(iOS 27.1, *) {
            registerForTraitChanges(
                UITraitCollection.systemTraitsAffectingVerticalBarEdge
            ) { [weak self] (_: DuoNavigationController, _: UITraitCollection) in
                self?.view.setNeedsLayout()
            }
        }
    }

    @objc private func railBackTapped() {
        popViewController(animated: true)
    }
}

如果导航控制器被更外层的 Tab 容器嵌套,应该由外层容器统一显示侧栏控件。不要让导航控制器和 Tab 容器各自创建一套返回按钮,否则会出现重叠。

18. 独立实现:Tab / Dock 容器

18.1 Dock 按钮视图

final class DuoDockView: UIView {
    let homeButton = UIButton(type: .system)
    let profileButton = UIButton(type: .system)

    var isVertical = false {
        didSet { setNeedsLayout() }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .systemBackground
        layer.cornerRadius = 8
        addSubview(homeButton)
        addSubview(profileButton)
        homeButton.setImage(UIImage(systemName: "house"), for: .normal)
        profileButton.setImage(UIImage(systemName: "person.crop.circle"), for: .normal)
        [homeButton, profileButton].forEach {
            $0.tintColor = .systemOrange
            $0.accessibilityLabel = $0 === homeButton ? "首页" : "个人中心"
        }
    }

    required init?(coder: NSCoder) { return nil }

    override func layoutSubviews() {
        super.layoutSubviews()
        let buttons = [homeButton, profileButton]
        for (index, button) in buttons.enumerated() {
            if isVertical {
                let height = bounds.height / CGFloat(buttons.count)
                button.frame = CGRect(x: 0, y: CGFloat(index) * height,
                                      width: bounds.width, height: height)
            } else {
                let width = bounds.width / CGFloat(buttons.count)
                button.frame = CGRect(x: CGFloat(index) * width, y: 0,
                                      width: width, height: bounds.height)
            }
        }
    }
}

18.2 Tab 容器布局

final class DuoTabBarController: UITabBarController, UINavigationControllerDelegate {
    private let dock = DuoDockView()
    private var lastSide: DuoRailSide = .none

    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.isHidden = true
        view.addSubview(dock)
        dock.homeButton.addTarget(self, action: #selector(showHome),
                                  for: .touchUpInside)
        dock.profileButton.addTarget(self, action: #selector(showProfile),
                                     for: .touchUpInside)
        dock.accessibilityIdentifier = "duo.dock"
        viewControllers?.compactMap { $0 as? UINavigationController }.forEach {
            $0.delegate = self
        }
        watchDuoTraits()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let side = DuoLayout.railSide(insets: view.safeAreaInsets,
                                      traits: traitCollection)
        let content = DuoLayout.contentFrame(in: view.bounds,
                                             insets: view.safeAreaInsets,
                                             traits: traitCollection)
        let isRoot = (selectedViewController as? UINavigationController)?
            .viewControllers.count == 1
        dock.isHidden = !isRoot

        if side == .none {
            let dockHeight: CGFloat = 64
            dock.isVertical = false
            dock.frame = CGRect(
                x: content.minX + 18,
                y: view.bounds.maxY - view.safeAreaInsets.bottom
                    - dockHeight - 12,
                width: max(0, content.width - 36),
                height: dockHeight
            )
        } else {
            dock.isVertical = true
            let rail = DuoLayout.railFrame(in: view.bounds,
                                           insets: view.safeAreaInsets,
                                           traits: traitCollection)
            dock.frame = CGRect(
                x: rail.minX + (rail.width - 58) * 0.5,
                y: view.bounds.midY - 66,
                width: 58,
                height: 132
            )
        }

        if side != lastSide {
            lastSide = side
            setNeedsStatusBarAppearanceUpdate()
        }
        view.bringSubviewToFront(dock)
    }

    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        view.setNeedsLayout()
    }

    private func watchDuoTraits() {
        if #available(iOS 27.1, *) {
            registerForTraitChanges(
                UITraitCollection.systemTraitsAffectingVerticalBarEdge
            ) { [weak self] (_: DuoTabBarController, _: UITraitCollection) in
                self?.view.setNeedsLayout()
            }
        }
    }

    @objc private func showHome() { selectedIndex = 0 }
    @objc private func showProfile() { selectedIndex = 1 }

    func navigationController(_ navigationController: UINavigationController,
                              willShow viewController: UIViewController,
                              animated: Bool) {
        view.setNeedsLayout()
    }
}

导航控制器保持全窗口大小,由 DuoNavigationController 调整页面内容 frame,并在侧栏绘制返回按钮;外层 Tab 容器只负责 Dock,避免两层同时扣减侧栏宽度。真实项目还应在根页面的滚动区域预留 Dock 高度;二级页无需底部 Dock 留白。

19. 业务页面示例

19.1 首页页面

final class HomeViewController: DuoViewController {
    private let scrollView = UIScrollView()
    private let detailButton = UIButton(type: .system)

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        navigationTitle = "Duo"
        showsBackButton = false
    }

    required init?(coder: NSCoder) { super.init(coder: coder) }

    override func viewDidLoad() {
        super.viewDidLoad()
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.alwaysBounceVertical = true
        contentView.addSubview(scrollView)
        NSLayoutConstraint.activate([
            scrollView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            scrollView.topAnchor.constraint(equalTo: contentView.topAnchor),
            scrollView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
        ])

        // 只放 UI 占位,不触发接口或 Loading。
        let card = makeCard(title: "示例卡片",
                            subtitle: "内容占位")
        scrollView.addSubview(card)
        card.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            card.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor,
                                          constant: 20),
            card.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor,
                                           constant: -20),
            card.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor,
                                      constant: 24),
            card.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor,
                                       constant: -40),
            card.heightAnchor.constraint(equalToConstant: 170),
            card.bottomAnchor.constraint(equalTo: detailButton.topAnchor,
                                         constant: -20)
        ])

        detailButton.setTitle("查看详情", for: .normal)
        detailButton.addTarget(self, action: #selector(detailTapped),
                               for: .touchUpInside)
        detailButton.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(detailButton)
        NSLayoutConstraint.activate([
            detailButton.leadingAnchor.constraint(
                equalTo: scrollView.contentLayoutGuide.leadingAnchor, constant: 20),
            detailButton.trailingAnchor.constraint(
                equalTo: scrollView.contentLayoutGuide.trailingAnchor, constant: -20),
            detailButton.widthAnchor.constraint(
                equalTo: scrollView.frameLayoutGuide.widthAnchor, constant: -40),
            detailButton.heightAnchor.constraint(equalToConstant: 48),
            detailButton.bottomAnchor.constraint(
                equalTo: scrollView.contentLayoutGuide.bottomAnchor, constant: -24)
        ])
    }

    private func makeCard(title: String, subtitle: String) -> UIView {
        let card = UIView()
        card.backgroundColor = .systemOrange
        card.layer.cornerRadius = 20
        let titleLabel = UILabel()
        titleLabel.text = title
        titleLabel.textColor = .white
        titleLabel.font = .systemFont(ofSize: 15, weight: .semibold)
        let amountLabel = UILabel()
        amountLabel.text = subtitle
        amountLabel.textColor = .white
        amountLabel.font = .systemFont(ofSize: 32, weight: .bold)
        let stack = UIStackView(arrangedSubviews: [titleLabel, amountLabel])
        stack.axis = .vertical
        stack.spacing = 8
        stack.translatesAutoresizingMaskIntoConstraints = false
        card.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 20),
            stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 20)
        ])
        return card
    }

    @objc private func detailTapped() {
        navigationController?.pushViewController(HomeDetailViewController(),
                                                 animated: true)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let reserve = DuoLayout.bottomContentReserve(in: view)
        scrollView.contentInset.bottom = reserve
        scrollView.verticalScrollIndicatorInsets.bottom = reserve
    }
}

19.2 首页二级页

final class HomeDetailViewController: DuoViewController {
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        navigationTitle = "详情"
    }

    required init?(coder: NSCoder) { super.init(coder: coder) }

    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.text = "这是首页的二级页面\n\n这里可以接入真实业务内容。"
        label.font = .systemFont(ofSize: 20, weight: .semibold)
        label.textColor = .label
        contentView.addSubview(label)
        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24),
            label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24),
            label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 32)
        ])
    }
}

若首页采用不同入口,也可复用相同的 push 方法:

@objc private func detailTapped() {
    navigationController?.pushViewController(
        HomeDetailViewController(),
        animated: true
    )
}

19.3 全屏登录页

final class LoginViewController: DuoViewController {
    override var fillsWindow: Bool { true }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        .lightContent
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.isHidden = true
        view.backgroundColor = .systemOrange
        let button = UIButton(type: .system)
        button.setTitle("进入首页", for: .normal)
        button.backgroundColor = .white
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(enterHome), for: .touchUpInside)
        view.addSubview(button)
        NSLayoutConstraint.activate([
            button.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor,
                                           constant: 24),
            button.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor,
                                            constant: -24),
            button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
                                          constant: -24),
            button.heightAnchor.constraint(equalToConstant: 52)
        ])
    }

    @objc private func enterHome() {
        let tabs = DuoTabBarController()
        tabs.viewControllers = [
            DuoNavigationController(rootViewController: HomeViewController()),
            DuoNavigationController(rootViewController: ProfileViewController())
        ]
        // viewDidLoad 尚未发生时,Tab 会在加载期间注册导航代理。
        view.window?.rootViewController = tabs
    }
}

19.4 个人中心占位页

final class ProfileViewController: DuoViewController {
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        navigationTitle = "个人中心"
        showsBackButton = false
    }

    required init?(coder: NSCoder) { super.init(coder: coder) }

    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel()
        label.text = "个人中心"
        label.font = .systemFont(ofSize: 20, weight: .semibold)
        label.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(label)
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
        ])
    }
}

20. 滚动区域和底部留白示例

底部 Dock 不能遮挡首页/个人中心最后一行内容。不要把固定的 -64 散落在各个页面,统一提供一个计算方法:

extension DuoLayout {
    static func bottomContentReserve(in view: UIView,
                                    dockHeight: CGFloat = 64) -> CGFloat {
        let side = railSide(insets: view.safeAreaInsets,
                            traits: view.traitCollection)
        if side != .none {
            // Dock 已在侧栏,不需要再扣横向 Dock 高度。
            return view.safeAreaInsets.bottom > 0 ? 0 : 20
        }
        let fallback: CGFloat = view.safeAreaInsets.bottom > 0 ? 0 : 20
        return dockHeight + fallback
    }
}

final class ListViewController: DuoViewController {
    private let tableView = UITableView(frame: .zero, style: .plain)

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(tableView)
        NSLayoutConstraint.activate([
            tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            tableView.topAnchor.constraint(equalTo: contentView.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
        ])
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let reserve = DuoLayout.bottomContentReserve(in: view)
        tableView.contentInset.bottom = reserve
        tableView.verticalScrollIndicatorInsets.bottom = reserve
    }
}

如果使用 Auto Layout 而不是直接设置 contentInset,也可以将列表底部约束到一个 Dock 顶部锚点;但在侧栏姿态下,该 Dock 不再位于底部,因此统一计算留白通常更稳定。

21. 状态栏样式示例

21.1 页面跟随姿态切换

override var preferredStatusBarStyle: UIStatusBarStyle {
    let side = DuoLayout.railSide(insets: view.safeAreaInsets,
                                  traits: view.traitCollection)
    return side == .none ? .lightContent : .darkContent
}

21.2 深色登录页保持浅色图标

final class DarkLandingViewController: DuoViewController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        .lightContent
    }

    // 如果外层容器会统一覆盖状态栏样式,可在容器中识别此属性,
    // 不要把所有页面强制设置成 darkContent。
    var keepsOwnStatusBarStyle: Bool { true }
}

21.3 容器转发状态栏样式

final class RootContainerViewController: UIViewController {
    override var childForStatusBarStyle: UIViewController? {
        children.first
    }
}

22. SceneDelegate 启动示例

适配逻辑不应该依赖 storyboard 自动创建 window。建议显式创建 window,确保根容器可以根据登录态切换:

final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?

    func scene(_ scene: UIScene,
               willConnectTo session: UISceneSession,
               options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = scene as? UIWindowScene else { return }

        let window = UIWindow(windowScene: windowScene)
        // 演示从静态登录页启动;可根据本地会话选择根容器。
        window.rootViewController = LoginViewController()
        window.makeKeyAndVisible()
        self.window = window
    }
}

23. 旋转、折叠和姿态变化测试代码

23.1 在开发环境输出关键几何信息

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    #if DEBUG
    let side = DuoLayout.railSide(insets: view.safeAreaInsets,
                                  traits: view.traitCollection)
    let content = DuoLayout.contentFrame(in: view.bounds,
                                         insets: view.safeAreaInsets,
                                         traits: view.traitCollection)
    print("Duo side: \(side), insets: \(view.safeAreaInsets), content: \(content)")
    #endif
}

23.2 手动触发容器重排

func invalidateDuoLayout() {
    view.setNeedsLayout()
    view.layoutIfNeeded()
    setNeedsStatusBarAppearanceUpdate()
}

23.3 UI 测试检查 Dock 方向

func assertDockLayout(in app: XCUIApplication) {
    let dock = app.otherElements["duo.dock"]
    XCTAssertTrue(dock.exists)
    XCTAssertTrue(dock.frame.width > 0)
    XCTAssertTrue(dock.frame.height > 0)
}

建议至少覆盖以下操作序列:

启动登录页
→ 登录按钮进入首页
→ 首页进入二级页
→ 返回首页
→ 切换个人中心
→ 切换 Duo 展开/折叠姿态
→ 再次进入首页二级页并返回

23.4 内容区计算单元测试

在单元测试 target 中导入宿主 App 模块(将 YourApp 替换为实际模块名)。这些测试不依赖 Duo 模拟器,可先验证几何计算;系统的 reserved regions 仍需在设备或模拟器上目测验证。

import XCTest
import UIKit
@testable import YourApp

final class DuoLayoutTests: XCTestCase {
    func testNoRailUsesFullBounds() {
        let bounds = CGRect(x: 0, y: 0, width: 390, height: 844)
        let insets = UIEdgeInsets(top: 59, left: 0, bottom: 34, right: 0)
        XCTAssertEqual(DuoLayout.railSide(insets: insets), .none)
        XCTAssertEqual(DuoLayout.contentFrame(in: bounds, insets: insets), bounds)
    }

    func testLeadingRailExcludesOnlyLeftInset() {
        let bounds = CGRect(x: 0, y: 0, width: 900, height: 600)
        let insets = UIEdgeInsets(top: 0, left: 74, bottom: 0, right: 0)
        XCTAssertEqual(DuoLayout.railSide(insets: insets), .leading)
        XCTAssertEqual(DuoLayout.contentFrame(in: bounds, insets: insets),
                       CGRect(x: 74, y: 0, width: 826, height: 600))
    }

    func testTrailingRailExcludesOnlyRightInset() {
        let bounds = CGRect(x: 0, y: 0, width: 900, height: 600)
        let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 64)
        XCTAssertEqual(DuoLayout.railSide(insets: insets), .trailing)
        XCTAssertEqual(DuoLayout.railFrame(in: bounds, insets: insets),
                       CGRect(x: 836, y: 0, width: 64, height: 600))
    }

    func testSmallHorizontalInsetsAreNotRail() {
        let insets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        XCTAssertEqual(DuoLayout.railSide(insets: insets), .none)
    }
}

24. 常见错误和修正方式

错误后果修正
通过 UIDevice 型号判断 Duo新机型或系统姿态变化失效使用 safeAreaInsets 和 reserved regions
只在启动时缓存安全区折叠、旋转后内容仍使用旧尺寸viewSafeAreaInsetsDidChange 后重新布局
在 trait 回调中直接读取安全区读取到变化前的旧值trait 回调只 setNeedsLayout,在 viewDidLayoutSubviews 读取
只用 verticalBarEdge 判定侧栏内屏竖屏误判为竖向侧栏先判断左右安全区是否达到阈值
侧栏和页面同时显示返回按钮出现两个返回按钮侧栏姿态下隐藏页面按钮
所有页面都扣侧栏宽度登录、相机等全屏页被裁切提供 fillsWindow 页面例外
仍使用系统 TabBar系统栏和自定义 Dock 重叠隐藏系统 TabBar,由容器统一布局
列表底部固定写 64侧栏姿态下多出空白或遮挡根据当前姿态计算 bottom reserve
直接使用 UIScreen.main.bounds内容宽度包含系统侧栏使用容器 contentFrame 或当前 view bounds
将整个 occlusion frame 当作图标区域侧栏按钮位置偏低使用 frame.inset(by: margins)

25. 交付前检查

独立接入完成后,应确认:

  1. 示例只依赖 UIKit,不需要网络层、共享单例或业务常量。
  2. 登录页、首页、个人中心和首页二级页都能在无网络环境下打开。
  3. 普通、展开竖屏、展开横屏和折叠外屏四种状态都能完成布局切换。
  4. viewDidLayoutSubviews、viewSafeAreaInsetsDidChange 和 trait 监听没有互相递归触发。
  5. 页面 push/pop 后内容 frame、侧栏按钮和 Dock 层级正确。
  6. 状态栏图标颜色符合页面背景和 Duo 侧栏规则。
  7. 最后一条列表内容不会被底部 Dock 遮挡。
  8. 横屏侧栏底色、顶部导航底色和页面背景色衔接自然。

备注:思路是自己的,适配是AI来做的,文档是AI写的

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/2301_77192008/article/details/168663202

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--