iOS开发 技术集锦iOS学习专题

UITextView的高度计算

2017-01-06  本文已影响261人  kiushuo

由于iOS10和iOS9的默认字体有区别,所以对相同宽度的字符串,当都超过一行时计算出来的高度不同。iOS10计算出来的高度偏大。

各种边距的UITextView

关于内边距问题:

如图所示:

再次认识UITextView与UITextField(图一).png

绿色的代表textView
红色的代表textView.textContainer
紫色的代表text

/*
   The inset of the text container's layout area within the text view's content area.
   This property provides text margins for text laid out in the text view. By default the value of this property is (8, 0, 8, 0).
   如图所示:textContainer距离上下的距离为8,距离左右的距离为0.
   */
let inset = textView.textContainerInset 
// inset = UIEdgeInsets(top: 8.0, left: 0.0, bottom: 8.0, right: 0.0)

/*  
  The amount by which text is inset within line fragment rectangles.
  The padding appears at the beginning and end of the line fragment rectangles. 
  The layout manager uses this value to determine the layout width. The default value of this property is 5.0.
  可以看出lineFragmentPadding为textContainer的属性,默认值为5.0,对应上图中 y = 5.0,即text距离textContainer的左右为5.0,上下为0.
 */
 let padding = textView.textContainer.lineFragmentPadding  // padding = 5.0

所以可以看出,真正的文字显示区域距离textView的上下左右是存在一定距离的,所以textView的实际size是大于text的实际size的。
如果想要使text能够在textView的完全展示出来,有两种处理方式:

textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, 0)
textView.textContainer.lineFragmentPadding = 0
// 或者
textView.textContainerInset = UIEdgeInsets(top: 0, left: -textView.textContainer.lineFragmentPadding, bottom: 0, right: -textView.textContainer.lineFragmentPadding)
let strHeight = stringHeight(textViewWidth - 2 * textView.textContainer.lineFragmentPadding...)
let textViewHeight = strHeight + 2 * 8

UITextField

再次认识UITextView与UITextField(图二).png
上一篇 下一篇

猜你喜欢

热点阅读