2015-08-31 52 views
0

在我的應用程序中,當用戶點擊shareToFacebook按鈕時,我需要我的應用程序從另一個已獲得分數的ViewController截取屏幕截圖,並將其分享到Facebook。所以我寫了這樣的代碼:(它工作得很好):如何通過截圖分享Facebook和Twitter(社交框架)?

@IBAction func sharetoFacebook() { 
var sharetoFacebook : SLComposeViewController = 
SLComposeViewController(forServiceType: 
SLServiceTypeFacebook) 
sharetoFacebook.setInitialText("WOW! I scored \(rightCounter) right..! Wanna challenge me?") 
shareToFacebook.addImage(UIImage(named: "//What should I put here ?")) 
self.presentViewController(sharetoFacebook, animated: 
    true, completion: nil) } 

現在,我的疑問是:爲了採取截圖從另一個視圖控制器已經拿到了分數,什麼代碼我應該投入這個:

shareToFacebook.addImage(UIImage(named: "//What should I put here ?")) 

順便說一句,在此先感謝!這將是一個很大的幫助!

+0

我不會把這個作爲一個答案,因爲我不是在我的機器並不能測試,但我想你想要做的就是使用'imageWithData'而不是你正在調用的默認創建者。從其他VC獲取數據並將其放入此處。這有點像使用Stream,如果你在.Net下熟悉它們的話。 –

回答

0

UIView創建擴展並具有快照方法。這將返回UIImage任何視圖,包括子視圖。

extension UIView { 

    func snapshot() -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale) 

     drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true) 

     let sreenshotImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return screenshotImage 
    } 
} 

如果你把這種方法在VC

func snapshot() -> UIImage { 
      UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, UIScreen.mainScreen().scale) 

      drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true) 

     let sreenshotImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return screenshotImage 
    } 
+0

那麼,我應該在哪裏放入代碼?它是帶有分數的ViewController嗎? –

+0

如果你把這個視圖控制器,然後將bounds.size替換爲self.view.bounds.size,並將self.bounds替換爲self.view.bounds – Vig

+0

而且,所以在IBAction中我應該把'shareToFacebook.addImage(UIImage (名爲:「\(screenshotImage)」))'?這會工作嗎?而且,它就像..當分享按鈕被點擊時,Facebook的發佈選項應該提供前面提到的ViewController的屏幕截圖。而那個帶有分數的ViewController應該不會顯示出來..! –

相關問題