我有一个水平 ScrollView ,我可以在其中动态添加 View 。 在 LTR 语言上一切正常,我从左到右一个接一个地添加 View 。 在 RTL 上,问题是 View 总是添加到滚动的左侧,而不是像其他 Controller 一样添加到右侧,真正奇怪的是, View 的顺序添加到了正确的位置在第一个 View 的左侧,因此它们从右到左排序,但在 -x 上的 ScrollView 之外。
这是我添加新 View 时的代码:
Tag* tag = [self.storyboard instantiateViewControllerWithIdentifier:@"tag" ];
[_scroller addSubview:tag.view];
[tags addObject:tag];
Tag* prev = nil
for (Tag* tag in tags)
{
if (prev == nil)
{
[_scroller addConstraint:[NSLayoutConstraint constraintWithItem:tag.view
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:_scroller
attribute:NSLayoutAttributeLeading
multiplier:1.0f
constant:0]];
}
else
{
[_scroller addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[prev]-10-[tag]"
options:0
metrics:nil
views:@{@"tag" : tag.view, @"prev" : prev.view}]];
}
[_scroller addConstraint:[NSLayoutConstraint constraintWithItem:tag.view
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:_scroller
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0]];
prev = tag;
}
这是一张图片,展示了它在 LTR 和 RTL 上的工作原理以及实际工作原理
最佳答案
UIScrollView
出现此行为的原因是您忘记附加 trailingAnchor
最后一个元素 (#4) 到 ScrollView 的 trailingAnchor
.
leadingAnchor
ScrollView 和元素 #1 都相互连接(见下面的绿色部分)。然而, ScrollView 的内容矩形自然地从原点 (0,0)
跨越到正坐标方向。向右、向下(+x, +y)
。在您的情况下, ScrollView 的内容大小为宽度 0
因为 ScrollView 的 leadingAnchor
之间没有任何内容和trailingAnchor
.
所以低于你的[_scroller addConstraints:_constraint];
添加类似(伪代码)的内容:
if tag == lastTag {
NSLAyoutconstraints.activate([
tag.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor)
])
}
关于ios - UIScrollView 与约束和 RTL 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22294536/