2016-03-04 39 views
0

我在CALayer中有一個按鈕,找不到添加圖像的方法。將圖像添加到遮罩層(CALayer)內的按鈕?

這是我的代碼。該按鈕出現,但....

 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 

回答

0

既然你嘗試添加按鈕的層子層設置圖像按鈕不起作用。一種方法是設置層內容如下,

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

以這種方式不能設置其它屬性,如按壓狀態等

+0

雖然此代碼段可以解決的問題,[包括一個解釋]( http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)真的有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – SmokeDispenser

+0

更新了我的答案。 –

+0

雖然這段代碼看起來很不錯,但我認爲masklayer需要參與。我運行代碼,它產生了「致命錯誤:意外地發現零,而解包可選值」 – JammyBugger