2014-12-05 77 views
5

我最近看到這個項目,用戶可以從一個自定義的鍵盤上點擊GIF,他們會看到一個「複製的」工具欄出現。我有一個問題:用UIPasteBoard複製圖像(Swift)

任何人都可以給我一些示例代碼來處理。我明白如何使用UIPasteboard及其函數,但是當我在此函數中輸入UTI類型「public.png」時,似乎無法使其工作:(我在Objective-c中注意到它是「@ public.png 」但我把‘public.png’我無法找到來源網上爲這個)

let imageURL = NSString(string:NSBundle.mainBundle().pathForResource("test", ofType: "png")!) 
     var data = NSData(contentsOfURL: NSURL(string:imageURL)!) 
     UIPasteboard.generalPasteboard().setData(data!, forPasteboardType: "public.png") 

回答

4

嘗試使用此代碼:

let image = UIImage(named: "myimage.png") 
UIPasteboard.generalPasteboard().image = image; 

你可以找到其工作原理here!

希望這會有所幫助

+0

我可能需要在物理設備上嘗試它。模擬器不會讓我看到我的「粘貼」圖像。 – Guled 2014-12-05 02:08:43

+1

這將是一個好主意。 iOS中有很多工具需要在物理設備上進行測試。 – user2277872 2014-12-05 02:11:39

7

使用UIPasteboard.generalPasteboard().image = image;時,看起來圖像未複製到粘貼板。而是嘗試下一個代碼,它也解釋瞭如何替換"public.png"字符串:

// The Pasteboard is nil if full access is not granted 
// 'image' is the UIImage you about to copy to the pasteboard 
if let pb = UIPasteboard.generalPasteboard() { 
    let type = UIPasteboardTypeListImage[0] as! String 
    if !type.isEmpty { 
     pb.setData(UIImagePNGRepresentation(image), forPasteboardType: type) 
     if let readData = pb.dataForPasteboardType(type) { 
      let readImage = UIImage(data: readData, scale: 2) 
      println("\(image) == \(pb.image) == \(readImage)") 
     } 
    } 
} 
+0

我會試試看。謝謝你的幫助。 – Guled 2015-05-13 23:36:25

+0

感謝它爲我工作。 – kb920 2016-01-06 06:31:35