Search code examples
swiftautolayoutright-to-left

Swift: Align view X points from center towards trailing edge


I have a UIImageView which should be placed 10 points from center of the parent UIView. In LTR it works fine but in RTL it should be -10 points.

Is there a way to align X points from center towards trailing edge? Or should I set the constraint manually based on the layout direction?


Solution

  • If you constrain the Leading anchor of the image view to the CenterX anchor of your view, with a Constant: 10, it will automatically swap to its Trailing anchor at -10 pts from the CenterX.

    Here's how you could do it via code:

        let imgView = UIImageView()
        imgView.backgroundColor = .systemYellow
        imgView.translatesAutoresizingMaskIntoConstraints = false
        if let img = UIImage(systemName: "person") {
            imgView.image = img
        }
        view.addSubview(imgView)
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            imgView.topAnchor.constraint(equalTo: g.topAnchor, constant: 100.0),
            imgView.widthAnchor.constraint(equalToConstant: 120.0),
            imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor),
            imgView.leadingAnchor.constraint(equalTo: g.centerXAnchor, constant: 10.0),
        ])
    

    Here's how it could look in Storyboard (the vertical red line is just a 1-pt wide view showing the horizontal center):

    enter image description here

    and at run-time, using RTL language (NO code at all):

    enter image description here