gpt4 book ai didi

swift - 如何显示稍微超出 UITextView 的字符的其余部分?

转载 作者:行者123 更新时间:2023-11-30 10:28:51 29 4
gpt4 key购买 nike

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

但是当使用这样的手写样式字体时,结束字符有时会在边缘被切断: enter image description here

我尝试使用text1.clipsToBounds = false,但没有显示字符的边缘。有没有办法在不改变 TextView 宽度的情况下显示完整字符?

这也是我用来设置 TextView 的代码:

    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)


}

谢谢!

更新:

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

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

最佳答案

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

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)
}
}

关于swift - 如何显示稍微超出 UITextView 的字符的其余部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59587781/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com