簡體   English   中英

左對齊子視圖到 UINavigationBar 大標題

[英]Left Aligning a subview to UINavigationBar Large Title

我有一個 UIViewController 作為 UINavigationController 的根,我設置了大標題的首選項,如下所示navigationController?.navigationBar.prefersLargeTitles = true

我的目標是將視圖的左側與導航標題的左側對齊,但我想動態而不是通過硬編碼值來實現。 這是所需的最終結果:

UINavigationBar 對齊

我嘗試使用導航欄標題的左側或 x position 檢索

let navigationLeftX = navigationController..navigationBar.layoutMargins.left

我還打印了這個值並得到了值8.0

所以我想,我應該將它設置為創建的視圖的 x position 並且它應該對齊,我在viewWillAppear中的代碼:

// Create a demo view
let demoView = UIView()
view.addSubview(demoView)
demoView.backgroundColor = .orange

// Get the current left margin of the nav title
let navigationLeftX = navigationController!.navigationBar.layoutMargins.left

// Add constraints to your view
demoView.translatesAutoresizingMaskIntoConstraints = false
demoView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: navigationLeftX).isActive = true
demoView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
demoView.widthAnchor.constraint(equalToConstant: 100).isActive = true
demoView.heightAnchor.constraint(equalToConstant: 100).isActive = true

結果很接近,但仍然很差。

UINavigationController UINavigationBar 與子視圖對齊

如果我將邊距 x 值加倍,它似乎正確對齊

// Get the current left margin of the nav title
let navigationLeftX = navigationController!.navigationBar.layoutMargins.left * 2

UINavigationBar 對齊 Swift

所以我正要得出結論,除了 8 點的左邊距之外,還有一個額外的 8 點填充,邏輯上認為,如果我將導航的左邊距設置為 0,我應該會看到 8 點的填充,所以我做了:

navigationController!.navigationBar.layoutMargins.left = 0

但令我驚訝的是,它實際上位於屏幕的左邊緣,沒有任何填充:

UINavigationBar 標題填充邊距對齊

任何人都可以解釋這種行為並分享動態對齊視圖與導航欄標題的最佳方式嗎?

提前致謝

另一個用戶問了一個類似的問題

我遇到了兩種可能賦予此價值的方法:

1.遍歷導航欄層次結構

var leftMargin: CGFloat = 0.0

for view in navigationController!.navigationBar.subviews
{
    if let classToFind = NSClassFromString("_UINavigationBarLargeTitleView"),
       view.isKind(of: classToFind)
    {
        leftMargin = view.layoutMargins.left
    }
}

// Set your left margin of view to align to leftMargin variable

這里的兩個未知數是我不確定這是否正在查詢私有 class 以及是否可以。 第二件事是,這個 class 名稱可能會在未來的 iOS 版本中更改。

2.systemMinimumLayoutMargins

我遇到的另一件事是獲取systemminimumlayoutmargins ,您可以這樣做:

var leftMargin = navigationController!.systemMinimumLayoutMargins.leading

// Set your left margin of view to align to leftMargin variable

這給出了一個有效的值,但是我不確定這是否是描述標題左側值的預期用途

我不會將此標記為已回答,以防有人提出更好的解決方案,但只是為任何可能有幫助的人指出這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM