Swfit
//Swift UIView 层次调整 // 将红色挪到最上边 view.bringSubviewToFront(redView) // 将蓝色挪到最下边 view.sendSubviewToBack(blueView) // 互换 view.exchangeSubview(at: 1, withSubviewAt: 2)
swfit示例代码
1 override func viewDidLoad() { 2 super.viewDidLoad() 3 4 view.backgroundColor = .white 5 createUI() 6 } 7 8 func createUI() { 9 10 let redView = UIView() 11 redView.backgroundColor = .red 12 view.addSubview(redView) 13 redView.snp.makeConstraints { (make) -> Void in 14 make.top.equalTo(view).offset(200) 15 make.left.equalTo(view).offset(50) 16 make.size.equalTo(CGSize( 200, height: 200)) 17 } 18 19 let greenView = UIView() 20 greenView.backgroundColor = .green 21 view.addSubview(greenView) 22 greenView.snp.makeConstraints { (make) -> Void in 23 make.top.equalTo(view).offset(250) 24 make.left.equalTo(view).offset(100) 25 make.size.equalTo(CGSize( 200, height: 200)) 26 } 27 28 29 let blueView = UIView() 30 blueView.backgroundColor = .blue 31 view.addSubview(blueView) 32 blueView.snp.makeConstraints { (make) -> Void in 33 make.top.equalTo(view).offset(300) 34 make.left.equalTo(view).offset(150) 35 make.size.equalTo(CGSize( 200, height: 200)) 36 } 37 38 //Swift UIView 层次调整 39 40 // 将红色View挪到最上边 41 view.bringSubviewToFront(redView) 42 // 将蓝色View挪到最下边 43 view.sendSubviewToBack(blueView) 44 // 互换 45 view.exchangeSubview(at: 1, withSubviewAt: 2) 46 }
Objective-C
//将一个视图放在另一个视图上面 - (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview; //将一个视图放在另一个视图下面 - (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview; //view在最上层 - (void)bringSubviewToFront:(UIView *)view; //view在最下层 - (void)sendSubviewToBack:(UIView *)view; // 使用 [self.view bringSubviewToFront:myView]; [self.view sendSubviewToBack:myView];