iOS swift UICollectionviewcell快照错误

时间:2017-04-20 07:25:40

标签: ios iphone swift uicollectionviewcell snapshot

当我试图在UICollectionview中拍摄某个UICollectionViewCell快照时,它是View的子视图,并在我的应用程序中在Facebook上分享...而Xcode抛出

  

致命错误:在解包可选值时意外发现nil

please click here for screenshot of that error

这是我的功能

func screenshotBSCell() {
        //Create the UIImage

        UIGraphicsBeginImageContext(CGSizeMake(bsCell.bounds.size.width, bsCell.bounds.size.height))
        ***self.bsCell.layer.renderInContext(UIGraphicsGetCurrentContext()!)***
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        //Save it to the camera roll
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

        //share the image to Social Media
        let composeSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
        composeSheet.setInitialText("Hello, Facebook!")
        composeSheet.addImage(image)

        presentViewController(composeSheet, animated: true, completion: nil)

    }

2 个答案:

答案 0 :(得分:0)

func screenshotBSCell( sender:AnyObject) {
        //Create the UIImage
        let indexpath = NSIndexPath.init(row: sender.tag, section: 0)

        self.bsCell = colletctionview!.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath ) as! bsCell
        UIGraphicsBeginImageContext(CGSizeMake(cell.bounds.size.width, cell.bounds.size.height))
        ***self.bsCell.layer.renderInContext(UIGraphicsGetCurrentContext()!)***
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        //Save it to the camera roll
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

        //share the image to Social Media
        let composeSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
        composeSheet.setInitialText("Hello, Facebook!")
        composeSheet.addImage(image)

        presentViewController(composeSheet, animated: true, completion: nil)

    }

使func成为this.it将解决您的问题。当您调用此函数时,它会为您创建单元格,因此它不会获得nil单元格

答案 1 :(得分:0)

现在正在进行最小的更改。谢谢大家!

 func screenshotPulseCell(sender: UIButton) {

    //Create the UIImage
    UIGraphicsBeginImageContext(plCell.frame.size)
    self.plCell.contentView.layer.renderInContext((UIGraphicsGetCurrentContext())!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

    //share the image to Social Media
    let composeSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
    composeSheet.setInitialText("My Pulse!")
    composeSheet.addImage(image)

    presentViewController(composeSheet, animated: true, completion: nil)

}