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 }

 

posted on 2019-01-08 12:02  活最好的自己  阅读(625)  评论(0编辑  收藏  举报

导航