我有多个按钮用10px填充(leadingPadding)分隔,如果是英文,则项目必须从左到右开始,如果是阿拉伯语从右到左,集中。
这是用于绘制scrollView的代码:
var previousView: UIView = self.itemsScrollView!
for i in 0..<self.items.count {
let sectionButton = UIButton(frame: CGRectZero)
sectionButton.titleLabel.text = "i = " + i
sectionButton.translatesAutoresizingMaskIntoConstraints = false
self.itemsScrollView!.addSubview(sectionButton)
// Left Constraint
let leftConstraint = NSLayoutConstraint(
item: sectionButton,
attribute: .Leading,
relatedBy: .Equal,
toItem: toView,
attribute: (toView === self.itemsScrollView!) ? .Leading : .Trailing,
multiplier: 1.0,
constant: leadingPadding);
self.itemsScrollView! .addConstraint(leftConstraint)
// Top Constraint
let topConstraint = NSLayoutConstraint(
item: sectionButton,
attribute: .Top,
relatedBy: .Equal,
toItem: self.itemsScrollView!,
attribute: .Top,
multiplier: 1.0,
constant: self.itemPaddingTopBottom);
self.itemsScrollView! .addConstraint(topConstraint)
// Width Constraint
let widthConstraint = NSLayoutConstraint(
item: sectionButton,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: buttonWidth);
self.itemsScrollView! .addConstraint(widthConstraint)
// Height Constraint
let heightConstraint = NSLayoutConstraint(
item: sectionButton,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: itemHeight);
self.itemsScrollView! .addConstraint(heightConstraint)
previousView = sectionButton
}
// add Trailing constraint on scroll
if (previousView !== self.itemsScrollView!) {
let leftConstraint = NSLayoutConstraint(
item: previousView,
attribute: .Trailing,
relatedBy: .Equal,
toItem: self.itemsScrollView!,
attribute: .Trailing,
multiplier: 1.0,
constant: 0.0);
self.itemsScrollView! .addConstraint(leftConstraint)
}
我假设这与使用scrollView的Trailing约束有关,但我不确定。如果是,有什么方法可以解决这个问题吗?
由于
答案 0 :(得分:0)
您不应直接在scrollview中添加多个视图。相反,您应该添加一个单独的容器视图,在scrollview中水平居中,其中应包含所有必需的子视图。容器视图的宽度必须由其子视图确定,因此第一个项目前导与容器前导对齐,最后一个项目尾部与LTR模式中的容器尾随对齐,或者第一个项目尾部与容器尾随对齐,最后一个项目前导是与RTL模式中的容器对齐