UITextView 文本缩放问题,具有不同的字体样式属性

时间:2021-06-11 05:07:24

标签: ios swift uitextview scaling nsattributedstring

enter image description hereenter image description here我只是想制作一个可缩放的拖动UITextView,我已经完成了拖动缩放在 textView 中使用单一字体。但问题是,当我尝试在 textView 中添加具有不同文本范围的不同字体样式时,我不知道如何在用手指缩放 textview 后计算字体大小。 因为每个自定义字体都有不同的尺寸。

这是我用来在 UITextView 缩放时增加和减小字体大小的代码。

 func updateTextFont(edgeInsets:UIEdgeInsets) {
        self.textContainerInset = UIEdgeInsets(top: (edgeInsets.top * frame.height),
                                               left: (edgeInsets.left * frame.width),
                                               bottom: (edgeInsets.bottom * frame.height),
                                               right: (edgeInsets.right * frame.width))
        if (self.text.isEmpty || self.bounds.size.equalTo(CGSize.zero)) { return;         }
        let textViewSize = CGSize(width: self.frame.width , height: self.frame.height);
        let fixedWidth = textViewSize.width;
        let expectSize = self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT)))
        var expectFont = self.font
        if (expectSize.height > textViewSize.height) {
            while (self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height > textViewSize.height && (self.font!.pointSize > CGFloat(1))) {
                expectFont = self.font!.withSize(self.font!.pointSize - 0.1)
                self.font = expectFont
            }
        }
        else {
            while (self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height < textViewSize.height && (self.font!.pointSize < CGFloat(1000))) {
                expectFont = self.font
                self.font = self.font!.withSize(self.font!.pointSize + 0.1)
            }
            self.font = expectFont
        }
    }

所以这里是我想将此方法转换为 NSAttributeString 的情况,我无法将单个字体分配给 textView。我想用 textView 边界缩放 attributeString。 在 SS 中,在第一个 SS 中,我使用属性字符串计算了框大​​小,在下一个 SS 中,我更改了框大小,但如何使属性字符串适合更新的框。这就是我面临的问题。

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要准确的字体大小值。但是如果可以使用最接近的字体值,您将使用算法解决此任务。

  1. 增大或减小所有字体的大小。 You can enumerate all attributes 的字符串与

    func enumerateAttribute(_ attrName: NSAttributedString.Key, 在 enumerationRange 中:NSRange, 选项选项:NSAttributedString.EnumerationOptions = [], 使用块:(Any?, NSRange, UnsafeMutablePointer) -> Void)

并根据比例增加或减少字体大小。
2. 之后你can calculate size of the string

func boundingRect(with size: CGSize, 
      options: NSStringDrawingOptions = [], 
      context: NSStringDrawingContext?) -> CGRect
  1. 对其他大小的字体重复此操作。

如果你计算不同字体大小的矩形,你会为 TextView 的边界取最接近的值。

我记得,您可以在并行线程的后台计算不同字体的大小。