如何本地化在 swift 中以编程方式添加的自动布局约束
How to localize Autolayout Constraint added programmatically in swift
在我的 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()
我的代码中是否遗漏了什么?或者我应该检查语言并手动翻转约束?
谢谢
你应该使用 .Leading
而不是 .Left
和 .Trailing
而不是 .Right
对于应该随着语言方向改变方向的东西。这就是 .Leading
和 .Trailing
的全部目的。
在我的 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()
我的代码中是否遗漏了什么?或者我应该检查语言并手动翻转约束?
谢谢
你应该使用 .Leading
而不是 .Left
和 .Trailing
而不是 .Right
对于应该随着语言方向改变方向的东西。这就是 .Leading
和 .Trailing
的全部目的。