Swift:在CALayer中添加自定义视图

时间:2014-11-04 15:21:08

标签: ios swift calayer

我尝试在CALayer中添加自定义视图。

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

我想把一些按钮和标签放在里面,但我担心我无法做到。我像这样制作CALabel:

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)
}

有可能做我想做的事吗?

非常感谢,请原谅我的英语水平

1 个答案:

答案 0 :(得分:9)

如果您创建UIView,则可以为此目的访问其layer媒体资源:

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)