微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – UIView的AirPrint内容

我正在尝试通过iPad应用程序设置打印,单击“打印”将打印包含其所有内容的视图.以下是我尝试过的内容(通过网上的几个例子汇总):
// This is the View I want to print
// Just a 200x200 blue square
var testView = UIView(frame: CGRectMake(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)

但是,我也读过here那个viewPrintFormatter只能用于UIWebView,UITextView和MKMapView,这是正确的吗?

当我用它打印(使用打印机模拟器)时,我只得到一个空页;试过各种打印机/纸张尺寸.

任何指导都非常感谢!

我不确定这是否是正确的方法,但我最终通过将视图转换为UIImage然后将其设置为打印控制器的printingItem来解决此问题.

更新的代码

// This is the View I want to print
// Just a 200x200 blue square
var testView = UIView(frame: CGRectMake(0,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,completionHandler: nil)

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
    }
}

如果有人有,可以选择其他方法

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐