如何本地化以编程方式快速添加的自动布局约束

Gra*_*ace 1 xcode localization autolayout nslayoutconstraint swift

在我的快速代码中,我使用自动布局约束。有些是直接从情节提要添加的,有些是以编程方式添加到 UIScrollView 上的。

当应用程序以阿拉伯语版本(RTL 方向)运行时,从故事板添加的自动布局约束会自动切换到 RTL 方向,而无需我做任何努力,但以编程方式添加到 UIScrollView 上的约束不会被翻转。

这是我在 UISCrollView 上添加约束的示例:

        var previousView: UIView = self.productsScrollView

        for productObj in productsArray {

            let productViewObj: ProductView = ProductView(frame: CGRectMake(0, 0, self.productsScrollView.frame.size.width, self.productsScrollView.frame.size.height), productObj: productObj)

            productViewObj.translatesAutoresizingMaskIntoConstraints = false
            self.productsScrollView.addSubview(productViewObj)


            // Left Constraint
            let leftConstraint = NSLayoutConstraint(item: productViewObj,
                attribute: .Left,
                relatedBy: .Equal,
                toItem: previousView,
                attribute: (previousView === self.productsScrollView) ? .Left : .Right,
                multiplier: 1.0,
                constant: 0.0);
            self.productsScrollView .addConstraint(leftConstraint)

            // Top Constraint
            let topConstraint = NSLayoutConstraint(item: productViewObj,
                attribute: .Top,
                relatedBy: .Equal,
                toItem: self.productsScrollView,
                attribute: .Top,
                multiplier: 1.0,
                constant: 0.0);
            self.productsScrollView .addConstraint(topConstraint)


            previousView = productViewObj

... // width, height constraints



}

...// and left constraint (for the last item) is added here

    self.productsScrollView.layoutIfNeeded()
Run Code Online (Sandbox Code Playgroud)

我的代码中是否缺少任何内容?或者我应该检查语言并手动翻转约束?

谢谢

Ken*_*ses 5

对于应该随语言方向改变方向的事物,您应该使用.Leading代替.Left.Trailing代替。这就是and.Right的全部目的。.Leading.Trailing