我正在尝试在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
答案 0 :(得分:0)
您可以尝试
self.mainView.insertSubview(focusBG, belowSubiew: tapView)
或
self.mainView.layer.insertSublayer(focusBG.layer, below: tapView.layer) // not tested
答案 1 :(得分:0)
尝试使用insertSublayer
,该方法对我有效。
self.mainView.layer.insertSublayer(your_Layer, at: 1) // 1 is the position of the layer you want to add to the mainView.
谢谢,让我知道这是否适合您。如果这样做,不要忘记投票;)