我有一个带有一堆 subview 的UIView
。我想根据所有 subview 的 y 位置 (frame.origin.y) 对它们的 z 顺序进行排序,这样:
if (view1.frame.origin.y > view2.frame.origin.y) --> View 1 的 z 顺序高于 View 2。
我可以删除所有 subview ,使用sortedArrayUsingComparator
对它们进行排序,然后以正确的顺序重新添加它们。然而,这会导致闪烁,我的目标是对它们全部进行排序,而不将它们从 super View 中删除。我猜测这可以使用排序算法加上 exchangeSubviewAtIndex
来完成,但我一直坚持实现它。
最佳答案
我为此使用的解决方案是:
NSArray *arraySorted = [self.subviews sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSComparisonResult result = NSOrderedSame;
if ([obj1 isKindOfClass:[MySubView class]] && [obj2 isKindOfClass:[MySubView class]]) {
MySubView *pin1 = (MySubView *)obj1;
MySubView *pin2 = (MySubView *)obj2;
result = pin1.frame.origin.y > pin2.frame.origin.y ? NSOrderedDescending : NSOrderedAscending;
}
return result;
}];
for (UIView *subview in arraySorted) {
[self bringSubviewToFront:subview];
}
关于ios - 根据位置对 UIView subview z 顺序进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809003/