2015-11-19 63 views
1

我有一个UIView与一堆子视图。我想根据它们的y位置(frame.origin.y)对所有子视图的z顺序进行排序,例如:根据位置排序UIView子视图z顺序

if(view1.frame.origin.y> view2.frame.origin。 y) - > view1具有比视图2更高的z顺序。

我可以删除所有子视图,使用sortedArrayUsingComparator对它们进行排序,然后按正确的顺序重新添加它们。但是,这会导致闪烁,我的目标是将它们全部排序而不将它们从超级视图中移除。我猜这可以使用排序算法加上exchangeSubviewAtIndex来完成,但是我坚持实现它。

回答

1

所以为了做到这一点,我建议在初始化时将标记设置为视图,以便稍后可以轻松找到它们。

这里我们要将视图y坐标添加到字典中,并将该关键字作为视图标记。假设这些是你唯一的标签子视图。否则有一个系统省略标签。

// Setting views and frames. 

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
NSMutableArray *objectArray = [[NSMutableArray alloc] init]; 
NSMutableArray *keyArray = [[NSMutableArray alloc] init]; 

for (UIView *view in self.view.subviews) { 

    if (view.tag) { 

     [dict setObject:[NSNumber numberWithFloat:view.frame.origin.y] forKey:[NSNumber numberWithInt:view.tag]]; 

    } 

} 

遍历字典并按降序插入y值。

for (NSNumber *keyNum in [dict allKeys]) { 

    float x = [[dict objectForKey:keyNum] floatValue]; 

    int count = 0; 

    if (floatArray.count > 0) { 

     for (NSNumber *num in floatArray) { 

      float y = [num floatValue]; 

      if (x < y) { 

       count++; 

       [floatArray insertObject:[NSNumber numberWithFloat:x] atIndex:count]; 
       [tagArray insertObject:keyNum atIndex:count]; 

       break; 
      } 

     } 

    }else{ 

     [floatArray insertObject:[NSNumber numberWithFloat:x] atIndex:count]; 
     [tagArray insertObject:keyNum atIndex:count]; 

    } 
} 

找回使用他们的标签和位置通过每一个迭代,并使用bringSubViewToFront方法的意见你的意见,这应该堆他们在正确的顺序。

注意:这里假定你没有在你的视图中需要在层次结构之上的其他子视图,如果是的话,我会使用insertSubview:AtIndex:方法。

for (NSNumber *num in tagArray) { 

    UIView *view = (UIView *)[self.view viewWithTag:[num integerValue]]; 

    NSLog(@"view.frame.origin.y: %.2f",view.frame.origin.y); 

    [self.view bringSubviewToFront:view]; 

} 
+0

我没有使用这个确切的解决方案,而是通过数组排序循环和使这一subivew到前面的概念解决了这个问题对我来说。标记正确。谢谢。 – Joel

2

我用于此的解决方案是:

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]; 
}