【问题标题】:How can I show the rest of a character that has gone slightly outside of UITextView?如何显示稍微超出 UITextView 的字符的其余部分?
【发布时间】:2020-01-05 09:03:26
【问题描述】:

我有一个 UITextView,它根据用户输入的文本(紫色框)改变大小,它位于另一个 UIView(红色框)内。

但是当使用这样的手写风格字体时,结尾字符有时会在边缘被截断:

我尝试过使用text1.clipsToBounds = false,但这并没有显示角色的边缘。有没有办法在不改变文本视图宽度的情况下显示完整字符?

这也是我用来设置文本视图的代码:

    let text1 = UITextView()
    text1.text = ""
    text1.font = UIFont(name: "Gotcha", size: 27)
    text1.frame = CGRect(x: 10, y: 5, width: 70, height: 50)
    text1.isScrollEnabled = false
    text1.delegate = self
    text1.textAlignment = .center
    text1.isEditable = false
    text1.isSelectable = false
    holdingView.addSubview(text1)

然后使用此函数更新框架,并且无论何时更改文本:

 func adjustTextViewSize(_ textView: UITextView) {

    let maxWidth = 300

    let newSize = textView.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude))

    textView.frame = CGRect(x: (textView.frame.minX), y: (textView.frame.minY), width: newSize.width, height: newSize.height)


}

谢谢!

更新:

我通过在newSize.width 中为任何手写字体添加额外的 30px 解决了这个问题:

if fontFile?.isHandwritten == true {
   currentView.widthConstraint?.constant = newSize.width + 30
   currentTextHoldingView.widthConstraint?.constant = newSize.width + 30
}

【问题讨论】:

  • 抱歉,我有点不清楚是什么问题。您将文本视图的宽度限制为 70,然后结果显示文本的宽度不够?
  • @matt 很抱歉造成混淆,我应该补充一点,文本视图会根据输入的内容而变化,因此值 70 只是一个临时起点 - 我已经编辑了问题以反映这个。 (屏幕截图也是冰岛输入的一个例子)
  • 好的,但是你正在做的不是回答“这个文本视图需要多宽才能以这种字体显示这个文本?”问题的正确方法

标签: swift uitextview


【解决方案1】:

调用该函数根据字符串长度获取高度

extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin,
                                            attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(boundingBox.height)
    }
}

【讨论】:

  • 我认为这里的问题是宽度,而不是高度
猜你喜欢
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
  • 2016-05-10
  • 1970-01-01
  • 2014-07-03
相关资源
最近更新 更多