控件的層級關系和你加入到父視圖的順序有關,也就是先addsubview至父視圖的,層級越低,會被后加入的遮蓋。
可以通過以下函數改變子視圖的層級
將一個UIView顯示在最前面:
- (void)bringSubviewToFront:(UIView *)view;
將視圖顯示在下面:
- (void)sendSubviewToBack...
例如下面的代碼示例:
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10, 50, 100, 50)]; view1.backgroundColor = [UIColor blueColor]; [self.view addSubview:view1]; UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(15, 55, 100, 50)]; view2.backgroundColor = [UIColor grayColor]; [self.view addSubview:view2]; //到這里位置時 view1 會在下面 view2會在上面 因為view2是后加到視圖上的 // 下面這行代碼能夠將view2 調整到父視圖的最下面 [self.view sendSubviewToBack:view2]; //下面這段代碼是 將view1調整到父視圖的最上面 [self.view bringSubviewToFront:view1];