Search code examples
iosswiftautolayoutios-autolayout

layout with before and after margins with equalToSystemSpacingAfter


I’m trying to change some layouts I have to a number-less layout. This is what I have for a segmented bar that should be inside a container view with something like this | - margin - segmented - margin -|

segmentedControl.leadingAnchor.constraint(equalToSystemSpacingAfter: margins.leadingAnchor, multiplier: 1),
segmentedControl.trailingAnchor.constraint(equalToSystemSpacingAfter: margins.trailingAnchor, multiplier: 1),

I know that the second line doesn’t make any sense, but I don’t see any equalToSystemSpacingBEFORE just after, and I’m not sure how to do it without having to rely only on layout propagation.

Basically, the leadingAchor works fine with this code, but the trailingAnchor (as the method name implies) adds the margin AFTER the trailing anchor, which is not what I want.

any ideas?


Solution

  • You can constrain the trailingAnchor of your "container" view relative to the trailingAnchor of your segmented control.

    Here's a quick example which I believe gives you the layout you want:

    class SysSpacingViewController: UIViewController {
    
        let seg: UISegmentedControl = {
            let v = UISegmentedControl(items: ["A", "B", "C"])
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()
    
        let cView: UIView = {
            let v = UIView()
            v.translatesAutoresizingMaskIntoConstraints = false
            v.backgroundColor = .white
            return v
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            view.backgroundColor = .systemYellow
    
            cView.addSubview(seg)
            view.addSubview(cView)
    
            let g = view.safeAreaLayoutGuide
            let m = cView.layoutMarginsGuide
    
            NSLayoutConstraint.activate([
    
                cView.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0),
                cView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
                cView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
                cView.heightAnchor.constraint(equalToConstant: 70.0),
    
                seg.leadingAnchor.constraint(equalToSystemSpacingAfter: m.leadingAnchor, multiplier: 1.0),
                m.trailingAnchor.constraint(equalToSystemSpacingAfter: seg.trailingAnchor, multiplier: 1.0),
    
                seg.centerYAnchor.constraint(equalTo: cView.centerYAnchor),
    
            ])
    
        }
    
    }
    

    Result:

    enter image description here