【问题标题】:UITextView text scaling issue , which is having different font styles attributesUITextView 文本缩放问题,具有不同的字体样式属性
【发布时间】:2021-06-11 05:07:24
【问题描述】:

Simply 我正在尝试制作一个可拖动的、可缩放的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 中我更改了框大小,但如何使属性字符串适合更新的框。这就是我面临的问题。

【问题讨论】:

    标签: ios swift uitextview scaling nsattributedstring


    【解决方案1】:

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

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

      func enumerateAttribute(_ attrName: NSAttributedString.Key, 在枚举范围: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 的边界取最接近的值。

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

    【讨论】:

    • 您好,感谢您的解决方案@Andrew,让我试试这个,我会尽快通知您。
    • 请查看截图一次。
    • 我只想要字体大小根据属性字符串的框大小。
    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多