简体   繁体   中英

setting leading margin of content to the leading of navigation bar large title in swift

I have a question about aligning content using autolayout.

I have a large navigation bar and one UIView right below the navigation bar. I want to set the UIView's leading anchor to the same leading anchor as the navigation bar. Currently, my code is something below and the view's leading anchor is not the same as the navigation bar's leading. (yes, because I'm using layoutMarginsGuide so that's why.)

NSLayoutConstraint.activate([
    myView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor),
    myView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor),
    myView.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor),
    myView.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor),
    myView.centerXAnchor.constraint(equalTo: self.centerXAnchor)
])

I used Figma and figured out the padding of large navigation bar (for iPhoneSE) was 16, so I can set the constraint for the myView's leading anchor as

myView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 16)

but I was wondering if there is a way to align without using a fixed constant value, 16?. I've looked up Safe Area Layout Guide and Layout Margins Guide, but I could not change the view as I wanted.

I came across two ways which could potentially give this value:

1. Iterating through the navigation bar hierarchy

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

The two unknowns here is I am not sure if this is querying a private class and if this is fine. The second thing is, this class name could change in future iOS releases.

2. systemMinimumLayoutMargins

Another thing I came across was getting the systemminimumlayoutmargins which you could do like this:

var leftMargin = navigationController!.systemMinimumLayoutMargins.leading

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

This gives a value which works, however I am not sure if this was the intended usage to depict the left value of the title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM