Проблема при вставке подслоя ниже существующего слоя в Swift? - PullRequest
0 голосов
/ 21 февраля 2019

Я пытаюсь добавить подслой позади существующего слоя в 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)
}

}

В идеале красная коробка должна быть перед серым слоем - но это то, что я получаю;screenshot1

Спасибо!

Обновление: рабочий код

        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

Ответы [ 2 ]

0 голосов
/ 21 февраля 2019

Попробуйте использовать insertSublayer, метод работает для меня.

self.mainView.layer.insertSublayer(your_Layer, at: 1) // 1 is the position of the layer you want to add to the mainView.

Спасибо и дайте мне знать, если это работает для вас.Не забудьте поднять голос, если это произойдет;)

0 голосов
/ 21 февраля 2019

Можно попробовать

self.mainView.insertSubview(focusBG, belowSubiew: tapView)

Или

self.mainView.layer.insertSublayer(focusBG.layer, below: tapView.layer) // not tested 
...