我是xcode和swift的初学者。
我的视图控制器中有几个字段和一个图像,我想打印此字段的内容...
我的教程代码:
@IBAction func print(sender: AnyObject) {
// 1
let printController = UIPrintInteractionController.sharedPrintController()
// 2
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "Rapport"
printController.printInfo = printInfo
// 3
let formatter = UIMarkupTextPrintFormatter(markupText: itemName.text!)
formatter.contentInsets = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)
printController.printFormatter = formatter
// 4
printController.presentAnimated(true, completionHandler: nil)
}
与这个唯一的文本字段配合得很好。但是我该如何打印其余部分呢?
您正在使用格式化程序发送到printController
,并向他发送要打印的标记文本。此函数采用一个字符串,因此您可以创建一个包含您希望它包含的所有文本的自定义字符串并调用该函数,如下所示:
// 3
let myMarkupText = itemName.text! + "n" + secondField.text! + "n" + anotherField.text!
let formatter = UIMarkupTextPrintFormatter(markupText: myMarkupText)
...
我添加了""来开始一个新行,但当然,您可以按照您想要的方式格式化它。我不确定""是否会创建一个新行(因为这是标记,也许你需要<br />
(,你必须尝试看看。
如果你想打印整个页面而不仅仅是某些部分,你也可以查看UIPrintInteractionController的文档,看看你还有什么其他选项(printingItem
、printingItems
、printPageRenderer
(。
或者,如果您有一个具有多个 回车符的长字符串,则需要先将所有 次替换为 br/,然后再将字符串提交到 UIMarkupTextPrintFormatter。 下面是 Swift 4 的示例:
func print(text: String) {
let textWithNewCarriageReturns = text.replacingOccurrences(of: "n", with: "<br />")
let printController = UIPrintInteractionController.shared
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.outputType = UIPrintInfoOutputType.general
printController.printInfo = printInfo
let format = UIMarkupTextPrintFormatter(markupText: textWithNewCarriageReturns)
format.perPageContentInsets.top = 72
format.perPageContentInsets.bottom = 72
format.perPageContentInsets.left = 72
format.perPageContentInsets.right = 72
printController.printFormatter = format
printController.present(animated: true, completionHandler: nil)
}