简体   繁体   中英

How to set NSImage to NSView Using CALayer in Cocoa swift

When I try to set NSimage to NSView my application gets crashed.

Application crashed at below line in ClockMainview controller: QuizDetailVC1.clockView.layer?.contents = a1 // here its a crash

class ViewController: NSViewController
    {
        var abc1 = ClockMain()
        @IBOutlet var clock view: NSView!
        let layer = CALayer()    
        func ClockApp()
        {
            layer.contents =  abc1.a1
            layer.contentsGravity = kCAGravityResizeAspectFill
            clockView?.layer = layer
            clockView?.wantsLayer = true
        }
    }

    class ClockMain: NSViewController,NSCollectionViewDelegate,NSCollectionViewDataSource
    {
     var a1 = NSImage(named:"\(UserDefaults.standard.value(forKey: "ImageName")!).jpg")!

      func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>)
        {
            let mainWC1 = view.window?.windowController as? Window
            let QuizDetailVC1 = storyboard?.instantiateController(withIdentifier: "ViewController") as! ViewController
            QuizDetailVC1.clockView.layer?.contents  = a1 // here its a crash
            QuizDetailVC1.layer.contentsGravity = kCAGravityResizeAspectFill
            mainWC1?.contentViewController = QuizDetailVC1
            print("click")
         }
    }

Try first setting this the line before:

QuizDetailVC1.clockView.wantsLayer = true
QuizDetailVC1.clockView.layer?.contents = a1

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