简体   繁体   English

将图像添加到蒙版图层(CALayer)内的按钮上?

[英]Adding an Image to a button inside a masklayer (CALayer)?

I have a button inside a CALayer and cannot find a way to add an image to it. 我在CALayer中有一个按钮,无法找到向其添加图像的方法。

Here is my code. 这是我的代码。 The button appears but.... 该按钮出现,但是....

        let button1 = UIButton(type: UIButtonType.Custom) as UIButton
        button1.frame = CGRectMake(36, 100 , 36, 36)
        button1.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)

         // Create your mask layer

        let maskLayer: CALayer = CALayer()
        maskLayer.frame = CGRectMake(0, 0, 250, 150)
        maskLayer.backgroundColor = UIColor.clearColor().CGColor
        maskLayer.addSublayer(button1.layer)
        maskLayer.contents = (UIImage(named: "RedDot.png")!.CGImage as! AnyObject)

        // Apply the mask to your uiview layer

        infoWindow.layer.addSublayer(maskLayer)



        return infoWindow

Since you are trying to add button's layer as sublayer setting image to the button doesn't work. 由于您尝试将按钮的图层作为子图层设置图像添加到按钮,因此无法正常工作。 One way is to set layer content as below, 一种方法是按如下所示设置图层内容,

    button1.layer.contents = (UIImage(named: "image.png")!.CGImage as! AnyObject)

In this way you can't set other properties like pressed state etc. 这样,您将无法设置其他属性,例如按下状态等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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