【问题标题】:swift UIPrintPageRenderer printableRect.size.width is always zero (0)swift UIPrintPageRenderer printableRect.size.width 始终为零 (0)
【发布时间】:2020-03-14 06:12:04
【问题描述】:

我正在使用 UIActivityViewController 进行打印(在其他活动中)​​。所以我将我的 UIPrintPageRenderer 的自定义子类的实例传递给它,相关代码如下。

本质上,我想打印两个多行属性字符串,并排,就像两列一样(最终,我希望将一个嵌入另一个并包裹起来,但不要领先于我们自己在这里)。右侧文本视图必须根据其内容固定大小(其子类覆盖 sizeToFit() 来实现这一点)。左侧文本视图应填充剩余的宽度。

所以我使用 UITextView 实例,填充属性字符串,并将它们各自的 .viewPrintFormatter()` 输出作为 UIPrintFormatters 分配给 UIPrintPageRenderer。

这部分有效。两个属性字符串都打印在页面上。

但是,它们在页面的左边缘彼此重叠打印。

除非我硬编码值,否则我尝试使用 UIEdgeInsets 来限制其打印失败。看来这是因为我在查询printableRect.size.width 时得到0(零)。

为什么我的 UIPrintPageRendere 的 printableRect 总是零宽度?

实现两个多行属性字符串并排打印的正确方法是什么?

class CustomPrintPageRenderer: UIPrintPageRenderer {
    let leftTextView = UITextView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    let rightTextView = IngredientsTextView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))

    init(_ thing: Thing) {
        super.init()
        addThing(thing)
    }

    func addThing(_ thing: Thing) {
        //  Do some stuff here to populate the two text views with attributed strings
        //  ...
        //  ...
        rightTextView.sizeToFit()
        let leftPrintFormatter = leftTextView.viewPrintFormatter()
        let rightPrintFormatter = rightTextView.viewPrintFormatter()
        print(paperRect.size.width)
        print(printableRect.size.width)
        rightPrintFormatter.perPageContentInsets = UIEdgeInsets(top: formatter.titleFontSize, left: printableRect.size.width - rightTextView.frame.size.width, bottom: 0, right: 0)
        leftPrintFormatter.perPageContentInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: rightTextView.frame.size.width)

        addPrintFormatter(leftPrintFormatter, startingAtPageAt: numberOfPages)
        addPrintFormatter(rightPrintFormatter, startingAtPageAt: numberOfPages)
    }
}

【问题讨论】:

    标签: ios swift printing uiedgeinsets uiprintpagerenderer


    【解决方案1】:

    我已经想通了。似乎 paperRect 和 printableRect 属性在 init() 时间不可用(这是我调用 addThing() 的地方)。

    我必须通过覆盖其他函数之一来完成这项工作,例如 drawPrintFormatter()numberOfPages()

    这主要按预期工作:

        override func drawPrintFormatter(_ printFormatter: UIPrintFormatter, forPageAt pageIndex: Int) {
            if printFormatter == rightPrintFormatter {
                printFormatter.perPageContentInsets = UIEdgeInsets(top: RecipeFormatter.titlePrintTextSize, left: printableRect.size.width - ingrWidth, bottom: 0, right: 0)
            } else if printFormatter == leftPrintFormatter {
                printFormatter.perPageContentInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: ingrWidth)
            }
            super.drawPrintFormatter(printFormatter, forPageAt: pageIndex)
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-26
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2016-09-22
      • 2019-09-21
      • 2017-09-05
      相关资源
      最近更新 更多