gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:47:39 31 4
gpt4 key购买 nike

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com