Jod*_*ner 5 uiview airprint uiprintformatter swift
我正在尝试通过iPad应用程序设置打印,单击"打印"将打印包含其所有内容的视图.以下是我尝试过的内容(通过网上的几个例子汇总):
// This is the View I want to print
// Just a 200x200 blue square
var testView = UIView(frame: CGRectMake(0, 0, 200, 200))
testView.backgroundColor = UIColor.blueColor()
let printInfo = UIPrintInfo(dictionary:nil)!
printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "My Print Job"
// Set up print controller
let printController = UIPrintInteractionController.sharedPrintController()
printController!.printInfo = printInfo
// This is where I was thinking the print job got the
// contents to print to the page??
printController?.printFormatter = testView.viewPrintFormatter()
// Do it
printController!.presentFromRect(self.frame, inView: self, animated: true, completionHandler: nil)
Run Code Online (Sandbox Code Playgroud)
但是,我也在这里看到viewPrintFormatter只有UIWebView,UITextView和MKMapView可用,这是正确的吗?
当我用它打印(使用打印机模拟器)时,我只得到一个空页; 试过各种打印机/纸张尺寸.
任何指导都非常感谢!
我不确定这是否是正确的方法,但我最终通过将视图转换为a UIImage然后将其设置为打印控制器来解决此问题printingItem.
更新的代码:
// This is the View I want to print
// Just a 200x200 blue square
var testView = UIView(frame: CGRectMake(0, 0, 200, 200))
testView.backgroundColor = UIColor.blueColor()
let printInfo = UIPrintInfo(dictionary:nil)!
printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "My Print Job"
// Set up print controller
let printController = UIPrintInteractionController.sharedPrintController()
printController!.printInfo = printInfo
// Assign a UIImage version of my UIView as a printing iten
printController?.printingItem = testView!.toImage()
// Do it
printController!.presentFromRect(self.frame, inView: self, animated: true, completionHandler: nil)
Run Code Online (Sandbox Code Playgroud)
该toImage()方法是UIView的扩展:
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人有,可以选择其他方法!