简体   繁体   中英

Swift: add custom view inside CALayer

I'm trying to add a custom view inside a CALayer.

http://i.imgur.com/sYzQ4kX.png

And I want to put inside some buttons and labels, but I'm afraid I'm not able to do it. I make the CALabel like this:

func addRectangleToLayer(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, layer: CALayer, index: UInt32 ) {
    var sublayer = CALayer()
    sublayer.backgroundColor = UIColor.whiteColor().CGColor
    sublayer.shadowOffset = CGSizeMake(0, 3);
    sublayer.shadowRadius = 5.0;
    sublayer.shadowColor = UIColor.blackColor().CGColor
    sublayer.shadowOpacity = 0.8;
    sublayer.cornerRadius = 12.0;
    sublayer.frame = CGRectMake(x, y, width, height);
    sublayer.borderColor = UIColor.blackColor().CGColor;
    sublayer.borderWidth = 0.5;

    //An example
    let label = UILabel()
    label.text = "LOREN"
    sublayer.contents = label

    layer.insertSublayer(sublayer, atIndex: index)
}

Is it possible to do what I want to?

Thanks a lot and excuse me for my english level

If you create a UIView , you'll have access to its layer property for this purpose:

let label = UILabel()
label.text = "LOREN"
var sublayer = label.layer;

// .. the rest of your layer initialization
sublayer.backgroundColor = UIColor.whiteColor().CGColor
sublayer.shadowOffset = CGSizeMake(0, 3);
sublayer.shadowRadius = 5.0;
sublayer.shadowColor = UIColor.blackColor().CGColor
sublayer.shadowOpacity = 0.8;
sublayer.cornerRadius = 12.0;
sublayer.frame = CGRectMake(x, y, width, height);
sublayer.borderColor = UIColor.blackColor().CGColor;
sublayer.borderWidth = 0.5;
// .. ended original source initialization

layer.insertSublayer(sublayer, atIndex: index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM