调整 UITextView 中的字体大小
如果文本太多,有没有办法缩小 UITextView 中的字体大小?类似于 UILabel?
Is there a way to shrink the font-size in a UITextView if there is too much text? Similar to the UILabel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
接受的答案的问题是您必须猜测填充该字段所需的字符数(字符串的长度),并且每个字体的字符数都不同。像这样的 UITextView 上的类别应该可以工作。
The problem with the accepted answer is that you have to guess the number of characters (the string's length) needed to fill the field, and that differs from font to font. Something like this, a category on UITextView, should work.
试试这个:
Try this:
Swift 4 实现的灵感来自 @Jane Sales 的回答。
在计算可用宽度和高度时,我们还必须考虑可能的垂直和水平边距(
textContainerInset
和textContainer.lineFragmentPadding
)。以下是对
UITextView
上边距如何工作的更好解释:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TextUILayer/Tasks/SetTextMargins.html如果文本视图可以调整大小,那么我们也必须强制布局,以便我们可以根据最大可能的文本视图大小来计算字体大小。在这种情况下,仅考虑高度(仅当所需文本高度大于原始可用高度时才布局)。
Swift 4 implementation inspired by @Jane Sales's answer.
When calculating available width and height we must also take into consideration possible vertical and horizontal margins (
textContainerInset
andtextContainer.lineFragmentPadding
).Here's a better explanation of how margins work on
UITextView
: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/TextUILayer/Tasks/SetTextMargins.htmlIf the text view can resize, then we must also force a layout so we can calculate the font size based on biggest possible text view size. In this case only height is considered (layouts only if required text height is bigger than original available height).