我正在尝试在Swift中添加一个现有图层后面的子图层,但子图层仍然在现有图层前面 - 我的代码中必须有问题;
import UIKit
class ViewController: UIViewController {
let mainView = UIView()
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let focusBG = UIView()
override func viewDidLoad() {
super.viewDidLoad()
mainView.backgroundColor = UIColor.gray
view.addSubview(mainView)
mainView.translatesAutoresizingMaskIntoConstraints = false
mainView.widthAnchor.constraint(equalToConstant: 325).isActive = true
mainView.heightAnchor.constraint(equalToConstant: ((325 / 9) * 16)).isActive = true
mainView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
mainView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
let tapView = UIView(frame: CGRect(x: 50, y: 0, width: 150, height: 200))
tapView.backgroundColor = UIColor.red
mainView.addSubview(tapView)
focusBG.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
focusBG.backgroundColor = UIColor(hue: 0.0, saturation: 0.0, brightness: 0.0, alpha: 0.4)
self.view.layer.insertSublayer(focusBG.layer, below: tapView.layer)
}
}
理想情况下,红色框将位于灰色图层的前面 - 但这正是我得到的;
谢谢!
更新:工作准则
self.mainView.insertSubview(focusBG, belowSubview: tapView)
focusBG.translatesAutoresizingMaskIntoConstraints = false
focusBG.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
focusBG.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
focusBG.widthAnchor.constraint(equalToConstant: screenWidth).isActive = true
focusBG.heightAnchor.constraint(equalToConstant: screenHeight).isActive = true
你可以试试
self.mainView.insertSubview(focusBG, belowSubiew: tapView)
要么
self.mainView.layer.insertSublayer(focusBG.layer, below: tapView.layer) // not tested
尝试使用insertSublayer
,方法适合我。
self.mainView.layer.insertSublayer(your_Layer, at: 1) // 1 is the position of the layer you want to add to the mainView.
谢谢,让我知道这是否适合你。如果确实如此,请不要忘记投票;)