简体   繁体   中英

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.

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.

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