ios - 根据位置对 UIView subview z 顺序进行排序

标签 ios objective-c sorting uiview

我有一个带有一堆 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/

相关文章:

objective-c - firemonkey + xcode,混合代码

在 lucene.net 中排序

c - 基于另一个数组顺序的数组排序

ios - 向 TabBar 应用程序添加 UI 导航

ios - 为什么 Obj-C 实例有 1 个保留计数刚创建?

ios - 如何知道推送的 View 何时停止移动。 UIKit 动态

IOS Core Telephony警告和应用商店查询

iphone - EXC_BAD_ACCESS错误

iphone - 我如何更改cocos2D中的默认启动图像?

java - 我怎样才能用数组替换我代码中的 ArrayList 并且它仍然有效?