如何在Swift UIView类中添加SubLayer到图层

时间:2017-09-25 08:30:39

标签: ios swift uiview

我创建了一个FirstView类作为UIView类,并在initializeViews()函数中添加了一个容器来添加一些图层,例如salamLogo和addSub图层

import UIKit
import QuartzCore

class FirstView: UIView {
    var container: UIView {
        let x = CGFloat(0.0),
        y = CGFloat(0.0),
        w = CGFloat(screenWidth),
        h = CGFloat(screenHeight - statusBarHeight)
        let view = UIView(frame: CGRect(x: x, y: y, width: w, height: h))
        view.background(color: UIColor.red)
        return view
    }

    var salamLogo: CALayer {
        let layer = CALayer()
        let view = UIImage(named: "sibdiet_logo")?.cgImage
        let x = CGFloat(screenWidth / 2 - 72.0),
        y = CGFloat(20.0),
        w = CGFloat(160.0),
        h = CGFloat(160.0)
        layer.frame = CGRect(x: x, y: y, width: w, height: h)
        layer.contents = view
        layer.contentsGravity = kCAGravityResizeAspect
        return layer
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeViews()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeViews()
    }
    private func initializeViews(){
        container.layer.addSublayer(salamLogo)
        addSubview(container)
    }

}
ViewController中的

从FirstView类添加对象和addSubView

import UIKit

var screenHeight: CGFloat =  UIScreen.main.bounds.height
let screenWidth: CGFloat =  UIScreen.main.bounds.width
let statusBarHeight = UIApplication.shared.statusBarFrame.height

class ViewController: UIViewController {

    var firstView:  FirstView!

    override func viewDidLoad() {
        super.viewDidLoad()

        screenHeight = screenHeight == 812 ? 788 : UIScreen.main.bounds.height

        firstView = FirstView(frame: CGRect(x: 0, y: statusBarHeight, width: screenWidth, height: screenHeight ))
        self.view.addSubview(firstView)

    }
}
模拟器中的

显示红框但不显示salamLogo图层或任何图层

1 个答案:

答案 0 :(得分:2)

添加图层与添加子视图非常相似:

layer.addSublayer(salamLogo)

但在您的情况下,使用子视图可能会更好吗?我没有看到在这里使用图层的任何目的。您可以将salamLogo定为常规UIImageView

======编辑=====

返回您的解决方案。您的代码中存在问题。每次拨打containersalamLogo,您都会创建新的UIView和新的CALayer。要只保留一个实例:

    lazy var container: UIView = {
        let x = CGFloat(0.0),
        y = CGFloat(0.0),
        w = CGFloat(screenWidth),
        h = CGFloat(screenHeight - statusBarHeight)
        let view = UIView(frame: CGRect(x: x, y: y, width: w, height: h))
        view.background(color: UIColor.red)
        return view
    }()

    lazy var salamLogo: CALayer = {
        let layer = CALayer()
        let view = UIImage(named: "sibdiet_logo")?.cgImage
        let x = CGFloat(screenWidth / 2 - 72.0),
        y = CGFloat(20.0),
        w = CGFloat(160.0),
        h = CGFloat(160.0)
        layer.frame = CGRect(x: x, y: y, width: w, height: h)
        layer.contents = view
        layer.contentsGravity = kCAGravityResizeAspect
        return layer
    }()