How to get UIView hierarchy index? (i.e. the depth in between the other subviews)

前端 未结 2 1522
时光说笑
时光说笑 2020-12-09 03:10

From UIView docs:

(void)insertSubview:(UIView *)view atIndex:(NSInteger)index

It\'s great that I can insert a UIView at a certain index, bu

2条回答
  •  無奈伤痛
    2020-12-09 03:27

    I am almost 100% sure that the index is the same as the index of the subView inside the superViews subviews property.

    UIView * superView = .... some view
    UIView * subView = .... some other view
    [superView insertSubview:subView atIndex:index];
    int viewIndex = [[superView subviews] indexOfObject:subView];
    // viewIndex and index should be the same
    

    I just tested this with the following code and it works

    UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    UIView* view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    UIView* view3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [self.view insertSubview:view1 atIndex:1];
    [self.view insertSubview:view2 atIndex:2];
    [self.view insertSubview:view3 atIndex:3];
    
    NSLog(@"%d", [[self.view subviews] indexOfObject:view1]); // Is 1
    NSLog(@"%d", [[self.view subviews] indexOfObject:view2]); // Is 2
    NSLog(@"%d", [[self.view subviews] indexOfObject:view3]); // Is 3
    
    [self.view bringSubviewToFront:view1];
    NSLog(@"%d", [[self.view subviews] indexOfObject:view1]); // Is end of array
    
    [self.view sendSubviewToBack:view1];
    NSLog(@"%d", [[self.view subviews] indexOfObject:view1]); // Is 0
    

提交回复
热议问题