UITextView的高度计算

作者: kiushuo | 来源:发表于2017-01-06 14:33 被阅读261次

    由于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的各种边距;
    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)
    
    • 计算text的高度时考虑边距因素
    let strHeight = stringHeight(textViewWidth - 2 * textView.textContainer.lineFragmentPadding...)
    let textViewHeight = strHeight + 2 * 8
    

    UITextField

    • UITextFieldletfViewrightView:
      如图所示,搜索输入框UITextField中有两个子试图,左侧的放大镜和右侧的话筒,这两个视图实际上是通过textViewletfViewrightView两个属性设置的。
    再次认识UITextView与UITextField(图二).png
    • UITextField使用的时候看上去文字距离边框也有距离,但实际上它和UITextView是不同的,它的距离是由于所选择的borderStyle造成的,这里需要注意一下。

    相关文章

      网友评论

        本文标题:UITextView的高度计算

        本文链接:https://www.haomeiwen.com/subject/hqkcvttx.html