1. 程式人生 > >iOS 分類:按順序新增檢視

iOS 分類:按順序新增檢視

一, 場景:

  1. 在一個父檢視上新增多個子檢視的情況下, 有可能出現新增檢視的時機有先後的問題, 後來的檢視會遮蓋住先來的檢視.
  2. 可以在新增子檢視的時候, 獲取需要展示的優先順序大小..優先順序越高, 就在已有檢視更外層顯示.

二, 分類方法程式碼如下:

1 // UIView+addsubview.h
2 
3 @interface UIView (addsubview)
4 @property (nonatomic,assign) NSInteger sort;
5 - (void)addsubviewBysort:(UIView *)newView ;
6 
7 @end
 1 //UIView+addsubview.m
 2 
 3 #import "UIView+addsubview.h"
 4 #import <objc/runtime.h>
 5 @implementation UIView (addsubview)
 6 - (void)setSort:(NSInteger)sort{
 7     objc_setAssociatedObject(self, @selector(setSort:), @(sort), OBJC_ASSOCIATION_ASSIGN);
 8 }
 9 
10 - (NSInteger)sort{
11
NSNumber *num = objc_getAssociatedObject(self, @selector(setSort:)); 12 return num.integerValue; 13 } 14 15 - (void)addsubviewBysort:(UIView *)newView { 16 BOOL bInsert = NO; 17 for (NSInteger i = self.subviews.count - 1; i >= 0 ; i--) { 18 UIView *subview = [self.subviews objectAtIndex:i];
19 if (subview.sort <= newView.sort) { 20 bInsert = YES; 21 NSLog(@"lz--insert->%li---on:%li",(long)newView.sort,(long)subview.sort); 22 [self insertSubview:newView aboveSubview:subview ]; 23 break; 24 } 25 } 26 if (bInsert == NO) { 27 NSLog(@"lz--below all->%li",(long)newView.sort); 28 [self insertSubview:newView atIndex:0]; 29 } 30 } 31 32 - (NSInteger)getMaxSort{ 33 NSInteger maxSort = 0; 34 for (UIView *subview in self.subviews) { 35 if (maxSort < subview.sort) { 36 maxSort = subview.sort; 37 } 38 } 39 return maxSort; 40 } 41 @end

三, 呼叫方式程式碼如下:

 1 - (void)test{
 2     for (int i = 100; i > 0; i--) {
 3         dispatch_async(dispatch_get_main_queue(), ^{
 4             UIView *view = [UIView new];
 5             view.sort = arc4random()%100;
 6             [self.view addsubviewBysort:view];
 7         });
 8     }
 9     
10     
11     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
12         for (UIView *subview in self.view.subviews) {
13             NSLog(@"lz-->%li",(long)subview.sort);
14         }
15     });
16 
17 }