2015-11-19 102 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]; 
}